2016-04-12 42 views
0

我正在寫一個我正在製作的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; 
    } 

我的問題是兩個,有什麼問題我目前的策略/實現,是有更簡單的辦法,我做到這一點(第一部分是更重要的)?

回答

0

您不是在一個幀之間存儲對象的方向。我認爲你正在考慮你正在創建的四元數是面向對象的新方向。但實際上,它只是一個四元數,它只表示最後一幀和當前幀之間的旋轉差異,而不是整體方向。

所以需要發生的是你的新quat必須被應用到最後一幀的方向四元數才能獲得當前的幀方向。

換句話說,您正在創建一個幀間更新四元數,而不是最後的方向四元數。

你需要做這樣的事情:

enemyCurrentOrientation = Quaternion.Concatenate(lastFrameQuat, thisNewQuat); 

有可能是一個更簡單的方法,但如果這樣的工作對你來說,沒有必要去改變它。

+0

這是有道理的,並幫助了。我的點積使用仍然存在一些問題,因爲有時它會導致對象抖動並感到困惑。我認爲它與反餘弦域有關,但不確定。 – computerscience32