# Simple Enemy AI

**URL:** https://forum.kirupa.com/t/simple-enemy-ai/208620
**Category:** programming
**Created:** [November 30, 2006, 2:57pm UTC](https://forum.kirupa.com/t/simple-enemy-ai/208620 "2006-11-30T14:57:49Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![bholaday](https://avatars.discourse-cdn.com/v4/letter/b/58f4c7/32.png) [@bholaday](https://forum.kirupa.com/u/bholaday)
#### Post date: [November 30, 2006, 2:57pm UTC](https://forum.kirupa.com/t/simple-enemy-ai/208620/1 "2006-11-30T14:57:49Z")

</div>

Hi,

I am creating a mega man-like game. I need some simple enemy movement code that needs to:

1. Activate the enemy’s movement only when the player is within a certain proximity of the enemy.
2. “Fly” (both enemies are bugs) towards the players’ registration point until it is killed.

That’s it. It seems pretty simple, but I am having trouble with it. Especially when the enemy reaches the registration point. It starts to go crazy. Here is an example of my code which uses simple pythagorean calculations:

```auto

function enemyMovement(enemy:String):Void {
    //movement calcs
    var run:Number = outScreen[enemy]._x - outScreen.megaman._x;
    var rise:Number = outScreen[enemy]._y - outScreen.megaman._y + 34; 
       //34 above accounts for registration point offset
    var distance:Number = Math.sqrt(Math.pow(rise,2) / Math.pow(run,2));
    var angle:Number = Math.pow(Math.tan(rise / run), -1);
    
    //actual movement
    outScreen[enemy]._x += Math.sin(angle);
    outScreen[enemy]._y += Math.cos(angle);
        
    
    //collision detection
    var bOverlap:Boolean = outScreen[enemy].hitTest(outScreen.megaman);
    
    //decrease health
    if (bOverlap) {
        decreaseHealth();
    }
}

```

Anyone posting can focus more on the movement as I will most likely be able to add the proximity aspect without trouble… ::fingers crossed::

Thanks,  
Blake
