Frage

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?

War es hilfreich?

Lösung

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)

Andere Tipps

something from my head in pseudo code.

Direction = Enemy.Position - Player.Position
Direction.Normalize()
Enemy.Position += Direction * Speed
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top