当我的对象到达我用鼠标点击的目的地时,我如何让它停止?代码使对象向鼠标点击点移动,但我似乎找不到如何使其停止,因为它几乎永远不会通过特定的目标点。:/谁知道如何做到这一点?
public function onMouseDown(evt:MouseEvent)
{
if (this._character != null)
{
_character.isMoving = false;
_character.dx = 0;
_character.dy = 0;
targetX = mouseX - _character.x;
targetY = mouseY - _character.y;
var angle:Number = Math.atan2(targetY,targetX);
var dx:Number = Math.cos(angle) * _character.speed;
var dy:Number = Math.sin(angle) * _character.speed;
_character.dx = dx;
_character.dy = dy;
_character.isMoving = true;
}
}
public function updateCharacter(e:Event):void
{
if (this._character.isMoving)
{
this._character.x += this._character.dx;
this._character.y += this._character.dy;
}
}
最简单的方法是计算每次移动时要停止的点的角度。如果你在直线上移动,直到你经过你试图停下来的点,这个值应该保持不变,在这个点上它会发生巨大的变化。
一旦发生这种情况,只需将对象移回它应该停止的位置,然后再进行渲染。
我为您创建了一个带有源代码的演示。有相当多的代码,所以你可以下载源代码,而不是在这里发布所有内容:
http://martywallace.com/testing/gotoPoint.zip
试试这个
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Guest extends MovieClip
{
var walkSpeed:Number = 5;
var oldPosX;
var oldPosY;
public function Guest()
{
stage.addEventListener(MouseEvent.CLICK, walk);
}
function walk(event:MouseEvent):void
{
oldPosX = parent.mouseX;
oldPosY = parent.mouseY;
rotation = Math.atan2(oldPosY - y,oldPosX - x) / Math.PI * 180;
addEventListener(Event.ENTER_FRAME, loop);
}
function loop(event:Event):void
{
// see if you're near the target
var dx:Number = oldPosX - x;
var dy:Number = oldPosY - y;
var distance:Number = Math.sqrt((dx*dx)+(dy*dy));
if (distance<walkSpeed)
{
// if you are near the target, snap to it
x = oldPosX;
y = oldPosY;
removeEventListener(Event.ENTER_FRAME, loop);
}
else
{
x = x+Math.cos(rotation/180*Math.PI)*walkSpeed;
y = y+Math.sin(rotation/180*Math.PI)*walkSpeed;
}
}
}
}
但是,请参阅我的答案中的代码,它应该解释如何移动和停止。
模拟中对象的移动