How to make an object move towards another object in C# XNA

偶尔善良 提交于 2019-12-08 05:13:36

问题


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?


回答1:


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)




回答2:


something from my head in pseudo code.

Direction = Enemy.Position - Player.Position
Direction.Normalize()
Enemy.Position += Direction * Speed


来源:https://stackoverflow.com/questions/20518218/how-to-make-an-object-move-towards-another-object-in-c-sharp-xna

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!