使用AS3停止Flash移动对象

时间:2012-06-27 18:48:42

标签: actionscript-3 flash-cs5

我使用AS3编写一个对象,以一定的速度从屏幕中的某个点移动到另一个点。我尝试了不同的代码,但我无法真正实现我想要的... 现在我正在使用以下代码:

var xVelocity:Number = 8;

addEventListener (Event.ENTER_FRAME, onVelocity);

function onVelocity (eventObject:Event):void
{
    animal0.x +=  xVelocity;
    animal0.y +=  yVelocity;
}

物体移动得很完美,但是我不能让它停在我想要的位置x ......它一直移动直到它到达屏幕的末端...... 我怎么能让它停在我想要的位置?或者如果你有更好的方法做到这一点......

由于

3 个答案:

答案 0 :(得分:0)

假设动物从左到右穿过屏幕,下面的代码一旦到达xDest就会阻止它移动。

var xVelocity:Number = 8;
var xDest = 300;//Destination point along X axis

addEventListener (Event.ENTER_FRAME, onVelocity);

function onVelocity (eventObject:Event):void
{
    if(animal0.x < xDest)
    {
        //only move animal0 so long as it has not reached the destination
        animal0.x +=  xVelocity;
        animal0.y +=  yVelocity;
    }
}

答案 1 :(得分:0)

你可以尝试一个补间引擎我认为greensock包是你最好的选择。 http://www.greensock.com/tweenmax/

答案 2 :(得分:0)

使用距离公式计算物体离目的地的距离,然后如果距离足够近,则将其锁定到您的确切坐标。

var dist:Number; // The distance between the object and its destination
var threshold:int = 3; //How close it has to be to snap into place
function onVelocity (eventObject:Event):void
{
    animal0.x +=  xVelocity;
    animal0.y +=  yVelocity;
    dist = Math.sqrt(Math.pow(xDest - animal0.x,2) + Math.pow(yDest - animal0.y,2));
    if(dist < threshold)
    {
        removeEventListener(Event.ENTER_FRAME, onVelocity);
        animal0.x=xDest; // Locks the object into the exact coordinates
        animal0.y=yDest;
    }

}

我正在制作的游戏遇到完全相同的问题,这就是我解决它的方法。