如何使用actionscript 3使对象相对于鼠标指针移动?

时间:2013-03-04 07:37:57

标签: 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 个答案:

答案 0 :(得分:1)

您拥有正确的旋转部分,现在您只需要将cossin分别用于xy轴。例如:

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;