theARTboy
where art meets design
AS3 basic enemy intelligence
Categories: flash, games

Sometimes you just want somebody to chase you.

[as3]
private function ai():void
{
//calc dist
var tempDist=Math.sqrt(Math.pow(player.x-enemy.x,2)+Math.pow(player.y-enemy.y,2));
//trace(tempDist);
if(tempDist<150)
{
enemy.rotation=Math.atan2((player.y-enemy.y),(player.x-enemy.x))/Math.PI*180;
//calc h or v move
if(Math.abs(player.x-enemy.x)>Math.abs(player.y-enemy.y))
{
//move toward player on x axis first
if(player.x>enemy.x)
{

//player is to the right of enemy

enemy.x+=2;

}

else

{

//player is to the left of enemy enemy.x-=2;

}

}

else

{

//move toward player on y axis first

if(player.y>enemy.y)

{

//player is below enemy

enemy.y+=2;

}

else

{

//player is above enemy

enemy.y-=2;

}

}

}

}
[/as3]

Leave a Reply

You must be logged in to post a comment.