2013-03-04 54 views
0

我正在製作一款遊戲,我希望我的角色在向前按下時向着鼠標指針移動,並使用方向鍵左右移動。如何使用actionscript 3使對象相對於鼠標指針移動?

這裏是我當前的代碼:

import flash.events.MouseEvent; 
//Event Listners 
stage.addChild(crosshair_mc); 
crosshair_mc.mouseEnabled = false; 
crosshair_mc.addEventListener(Event.ENTER_FRAME, fl_CustomMouseCursor); 

function fl_CustomMouseCursor(event:Event) 
{ 
    crosshair_mc.x = stage.mouseX; 
    crosshair_mc.y = stage.mouseY; 
} 
Mouse.hide(); 

stage.addEventListener(MouseEvent.MOUSE_MOVE,facecursor); 
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_KeyboardDownHandler); 
//Functions 
function facecursor(event):void 
{ 
    character_mc.rotation = (180 * Math.atan2(mouseY - character_mc.y,mouseX - character_mc.x))/Math.PI + 90; 

} 


function fl_KeyboardDownHandler(event:KeyboardEvent):void 
{ 
    trace("Key Code Pressed: " + event.keyCode); 
    if (event.keyCode == 38) 
    { 
     character_mc.y = character_mc.y - 5; 
    } 
    if (event.keyCode == 40) 
    { 
     character_mc.y = character_mc.y + 5; 
    } 
     if (event.keyCode == 39) 
    { 
     character_mc.x = character_mc.x + 5; 
    } 
     if (event.keyCode == 37) 
    { 
     character_mc.x = character_mc.x - 5; 
    } 

} 

回答

1

你必須轉動件正確的,現在你需要的是分別包括與cossinxy軸。例如:

var speed:Number = 8; 
var angle:Number = Math.atan2(mouseY - character_mc.y, mouseX - character_mc.x); 

character_mc.rotation = angle * 180/Math.PI; 
character_mc.x += Math.cos(angle) * speed; 
character_mc.y += Math.sin(angle) * speed; 

爲了避免混淆,我會停止添加90度上旋轉,而是旋轉圖形面對右/東側。

打擊事物使用相同的邏輯,你只是想要在任何你想要的方向上旋轉四分之一的圓。僅供參考,以弧度圓的四是PI/2。有一個圈子裏2個PI弧度:

// Augment angle for strafing. 
angle += Math.PI/2; 
+0

@ user2130844但是你想它與你的代碼實現... – Marty 2013-03-04 08:48:40

+0

肯定的,但如何將我實現它使它做我想做的事情,因爲我之前只是用舊的代碼替換了它,並且使得character_mc跟着光標 – user2130844 2013-03-04 08:57:25

+0

@ user2130844是的,所以只需在按下適當的時候更新x和y像你這樣的密鑰有原始代碼。 – Marty 2013-03-04 09:03:55