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?

有帮助吗?

解决方案

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)

其他提示

something from my head in pseudo code.

Direction = Enemy.Position - Player.Position
Direction.Normalize()
Enemy.Position += Direction * Speed
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top