Question

I'm currently trying to make an object move towards another. I have this code so far to try and achieve it.

double angleRad = Math.Atan2(mdlPosition.Z+treeTransform.Translation.Z, mdlPosition.X-treeTransform.Translation.X);

enemyPos.X += (float)Math.Cos(angleRad) * 0.2f;
enemyPos.Z += (float)Math.Sin(angleRad) * 0.2f;

Whenever I move my player character, the object moves, but not towards the characters current position. How can I direct it towards current position?

Was it helpful?

Solution

Normally you should act in this way. I suppose you want that the enemy will move toward the player.

Vector2 dir = player.Position - enemy.Position;
dir.Normalize();

Now you only have to do every cycle:

enemy.Position += dir * speed;

EDIT

To make the enemy face the player try calculate the angle of dir and set it as rotation parameter of your draw call. You should achieve this using Math.Atan2(dir.Y, dir.X)

OTHER TIPS

something from my head in pseudo code.

Direction = Enemy.Position - Player.Position
Direction.Normalize()
Enemy.Position += Direction * Speed
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top