0
我在c#xna上做了一個自頂向下的2D rpg遊戲,用於我在大學的遊戲設計課。我正在嘗試創建一個簡單的AI,將敵人移向玩家。目前我的代碼如下XNA矢量數學運動
/// <summary>
/// method to move the enemy
/// </summary>
/// <param name="target">the position of the target</param>
/// <returns>the new position to be moved to</returns>
public virtual Vector2 move(Vector2 target)
{
Vector2 temp = (target - Position); // gets the difference between the target and position
temp.Normalize(); // sets the vector to unit vector
temp *= moveSpeed; // sets the vector to be the length of moveSpeed
float x = temp.X;
float y = temp.Y;
float xP, yP;
double angle = Math.Acos(((x * direction.X) + (y * direction.Y))/(temp.Length() * direction.Length())); //dot product finds the angle between temp and direction
angle *= agility; //gets the angle to move based on agility
xP = (float)(Math.Cos(angle) * (x - direction.X) - Math.Sin(angle) * (y - direction.Y) + x);
yP = (float)(Math.Sin(angle) * (x - direction.X) - Math.Cos(angle) * (y - direction.Y) + y); // these lines rotate the point x,y around the direction vector by angle "angle"
return new Vector2(xP, yP);
}
在正確的目標是通過在更新方法:
/// <summary>
/// updates the enemy
/// </summary>
public void update()
{
this.Position = move(Game1.player.Position);
}
但敵人並沒有移動。我將代碼添加到構造函數中,確保敏捷性和移動速度不爲0.更改這些值什麼也不做。
感謝您的任何幫助。
爲什麼不使用'Dot'方法? – phoog
您也可以使用'Math.Atan2((PlayerPosition.Y - EnemyPosition.Y),(PlayerPosition.X - EnemyPosition.Y));'來計算角度。我發現它更易於閱讀和理解。 –