如何使一个对象移动到C#XNA中的另一个对象 [英] How to make an object move towards another object in C# XNA
问题描述
我目前正在尝试使一个物体移向另一个物体.到目前为止,我已经有这段代码可以尝试并实现.
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;
编辑
要使玩家面对敌人,请尝试计算dir
的角度并将其设置为抽奖电话的rotation
参数.您应该使用Math.Atan2(dir.Y, dir.X)
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)
这篇关于如何使一个对象移动到C#XNA中的另一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!