簡體   English   中英

確定統一旋轉角色的方向?

[英]Determining which direction to rotate a character in unity?

我目前在嘗試確定哪個方向是兩個角度之間的最短路徑時遇到了很多問題。 我正在 Unity2D 中編寫一個 boid,並且我正在研究分離方面。 就上下文而言,我當前的系統通過在 boid 周圍創建指定數量的游戲對象來工作(我發現其中 16 個工作得很好)。 這些游戲對象有自己的腳本,可以將 linecast 繪制到父 boid,並記錄它與玩家的角度。 如果 linecast 撞到牆壁或 boid,它會將其角度的余弦和正弦添加到存儲在父 boid 中的兩個單獨列表中。 父 boid 計算這兩個列表的平均值並基於此創建一個向量。 boid 獲得該矢量的角度,並將其添加 180 度以找到它需要前進的方向,以免撞到 object。 聽起來效率極低,但這是我能想到的唯一方法,而且效果很好。

現在,不起作用的是向那個目標方向旋轉身體。 我不希望 boid 立即鎖定到 position,而是緩慢旋轉。 我想要這個,因為它為身體的運動增加了很多變化。 運動采用 boid 所面對的當前方向並以該方向移動。 在大多數情況下,我得到了這個代碼:

void Rotate()
    {
        if (currentRotation != goalRotation)
        {
            int sign = (currentRotation < goalRotation) ? 1 : -1;
            rotateSpeed = Mathf.Abs(currentRotation - goalRotation) / 10;
            currentRotation += rotateSpeed * sign;
            if (Mathf.Abs(currentRotation - goalRotation) <= .5) //If the current rotation is close, just make it the goal rotation.
            {
                currentRotation = goalRotation;
            }
        }
    }

(角度基於單位圓)

我真的很喜歡它如何開始快速旋轉 boid,並在 boid 達到所需角度時減慢速度。 因此,此代碼有效,除非當前旋轉是 350 度,而目標方向是 10 度。 即使最短的路徑是逆時針的,boid 也會順時針旋轉。 我確切地知道為什么,但不知道如何解決它。 任何幫助,將不勝感激。

我不明白boid是什么,但這是解決方案:

不光滑

transform.LookAt(target);

光滑的

var targetRotation = Quaternion.LookRotation(targetObj.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);

您可以結合Quaternion.RotateTowardsQuaternion.Slerp來實現超平滑的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM