Search code examples
actionscript-3flash-cs5

Stop a Flash moving object with AS3


I am used AS3 to programme an obect moving from certain point in the screen to another at a certain speed. I tried with different codes but i can't really achieve what I am looking for... Now i am working with the following code:

var xVelocity:Number = 8;

addEventListener (Event.ENTER_FRAME, onVelocity);

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

The object moves perfectly but i can't make it stop in the position x that i want...it keeps on moving till it reaches the end of the screen... How can i make it stop at the point I want? or if you have a better way to do that....

Thanks


Solution

  • Use the distance formula to calculate how far the object is from its destination, then if it's close enough, lock it in to your exact coordinates.

    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;
        }
    
    }
    

    I had the exact same issue with a game I'm creating, and this is how I solved it.