Friday 21 December 2012

character random movement on stage as3

var iswalking = false;
var goX = char.x;
var goY = char.y;
var movespeed = 1;
var dir = "down";
var previousDistance:Number = 0;
var currentDistance:Number = 0;
var totalDistance:Number;

goX = Math.floor(Math.random() * (1+ (stage.stageWidth + char.width) + char.width) - char.width);
goY = Math.floor(Math.random() * (1+ (stage.stageHeight + char.height) + char.height) - char.height);

stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(Event)
{// animation handling

    var GetDistance = Math.sqrt(Math.pow(char.x - this.goX,2) + Math.pow(char.y - this.goY,2));
    trace(GetDistance);


    if (iswalking == true)
    {
        char.w.play();
    }
    else
    {
        char.w.gotoAndStop(1);
    }
    // direction handling;
    char.gotoAndStop(dir);
    // movement handling;
    if ((goY-movespeed)>char.y)
    {
        char.y +=  movespeed;
        dir = "down";
        iswalking = true;
    }
    else if ((goY+movespeed)<char.y)
    {
        char.y -=  movespeed;
        dir = "up";
        iswalking = true;
    }
    else if ((goX-movespeed)>char.x)
    {
        char.x +=  movespeed;
        dir = "right";
        iswalking = true;
    }
    else if ((goX+movespeed)<char.x)
    {
        char.x -=  movespeed;
        dir = "left";
        iswalking = true;
    }
    else
    {
        iswalking = false;
        goX = Math.floor(Math.random() * (1+ (stage.stageWidth + char.width) + char.width) - char.width);
        goY = Math.floor(Math.random() * (1+ (stage.stageHeight + char.height) + char.height) - char.height);

    }
}

No comments:

Post a Comment