我正在寫一個我正在製作的3D遊戲的敵人類,並且正在努力讓敵人跟隨玩家。我希望敵人基本上在玩家的方向上每幀稍微旋轉一下,然後每幀向前移動一下。我嘗試使用Lerping來完成此操作,如下面的代碼所示,但我似乎無法使其工作。在玩時,敵人甚至不會出現在我的視野中,也不會出現在我的視野中。下面是我的敵人級別下面的代碼。C#和XNA - 如何使3D模型跟隨使用lerp的另一個3D模型
注意:p是對我追逐的玩家對象的引用,world是敵方物體的世界矩陣,quaternion是這個敵方物體的四元數。
我目前的策略是找到我的敵人的前向矢量和玩家的位置矢量3之間的方向矢量,然後用由速度變量確定的數量來確定方向矢量。然後,我嘗試找到由敵人的前向矢量確定的平面的垂直矢量,並且將新的矢量稱爲midVector。然後,我更新四元數以使玩家圍繞該垂直矢量旋轉。這是下面的代碼:
//here I get the direction vector in between where my enemy is pointing and where the player is located at
Vector3 midVector = Vector3.Lerp(Vector3.Normalize(world.Forward), Vector3.Normalize(Vector3.Subtract(p.position,this.position)), velocity);
//here I get the vector perpendicular to this middle vector and my forward vector
Vector3 perp=Vector3.Normalize(Vector3.Cross(midVector, Vector3.Normalize(world.Forward)));
//here I am looking at the enemy's quaternion and I am trying to rotate it about the axis (my perp vector) with an angle that I determine which is in between where the enemy object is facing and the midVector
quaternion = Quaternion.CreateFromAxisAngle(perp, (float)Math.Acos(Vector3.Dot(world.Forward,midVector)));
//here I am simply scaling the enemy's world matrix, implementing the enemy's quaternion, and translating it to the enemy's position
world = Matrix.CreateScale(scale) * Matrix.CreateFromQuaternion(quaternion) * Matrix.CreateTranslation(position);
//here i move the enemy forward in the direciton that it is facing
MoveForward(ref position, quaternion, velocity);
}
private void MoveForward(ref Vector3 position, Quaternion rotationQuat, float speed)
{
Vector3 addVector = Vector3.Transform(new Vector3(0, 0, -1), rotationQuat);
position += addVector * speed;
}
我的問題是兩個,有什麼問題我目前的策略/實現,是有更簡單的辦法,我做到這一點(第一部分是更重要的)?
這是有道理的,並幫助了。我的點積使用仍然存在一些問題,因爲有時它會導致對象抖動並感到困惑。我認爲它與反餘弦域有關,但不確定。 – computerscience32