有人告訴我,這Rigidbody.MoveRotation是 Unity 3D 中在固定位置之間旋轉玩家同時仍然檢測命中的最佳方式。但是,雖然我可以通過以下方式平穩地從固定位置移動到位置:
if (Vector3.Distance(player.position, targetPos) > 0.0455f) //FIXES JITTER
{
var direction = targetPos - rb.transform.position;
rb.MovePosition(transform.position direction.normalized * playerSpeed * Time.fixedDeltaTime);
}
我不知道如何在固定位置之間平滑旋轉。我可以立即使用旋轉到我想要的角度Rigidbody.MoveRotation(Vector3 target);,但我似乎無法找到一種方法來執行上述旋轉。
注意:Vector3.Distance是唯一停止抖動的方法。有沒有人有任何想法?
uj5u.com熱心網友回復:
您可以更進一步,使用推文庫在旋轉之間進行補間。
DOTween
有了它,你可以這樣稱呼它:
transform.DoRotate(target, 1f)在 1 秒內旋轉到目標。
甚至添加回呼。
transform.DoRotate(target, 1f).OnComplete(//any method or lambda you want)
uj5u.com熱心網友回復:
首先MoveRotation不需要 aVector3而是 a Quaternion。
那么一般來說,您的抖動可能來自超調- 您可能移動得比您的玩家和目標之間的實際距離更遠。
您可以通過使用Vector3.MoveTowards防止目標位置的任何過沖來避免該位,例如
Rigidbody rb;
float playerSpeed;
Vector3 targetPos;
// in general ONLY g through the Rigidbody as soon as dealing wit Physics
// do NOT go through transform at all
var currentPosition = rb.position;
// This moves with linear speed towards the target WITHOUT overshooting
// Note: It is recommended to always use "Time.deltaTime". It is correct also during "FixedUpdate"
var newPosition = Vector3.MoveTowards(currentPosition, targetPos, playerSpeed * Time.deltaTime);
rb.MovePosition(newPosition);
// [optionally]
// Note: Vector3 == Vector3 uses approximation with a precision of 1e-5
if(rb.position == targetPos)
{
Debug.Log("Arrived at target!");
}
然后,您可以通過Quaternion.RotateTowards基本相同的方法簡單地將相同的概念應用于旋轉
Rigidbody rb;
float anglePerSecond;
Quaternion targetRotation;
var currentRotation = rb.rotation;
var newRotation = Quaternion.RotateTowards(currentRotation, targetRotation, anglePerSecond * Time.deltaTime);
rb.MoveRotation(newRotation);
// [optionally]
// tests whether dot product is close to 1
if(rb.rotation == targetRotation)
{
Debug.Log("Arrived at rotation!");
}
uj5u.com熱心網友回復:
因此,您希望隨著時間的推移對旋轉值進行影片處理,直到達到某個值。
在 Update 方法中,您可以使用 Lerp 方法將物件保持旋轉到一個點,但如果您使用 Lerp,您將永遠不會真正到達該點。它將永遠旋轉(總是更接近點)。
您可以使用以下內容:
private bool rotating = true;
public void Update()
{
if (rotating)
{
Vector3 to = new Vector3(20, 20, 20);
if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)
{
transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);
}
else
{
transform.eulerAngles = to;
rotating = false;
}
}
}
因此,如果當前物體角度和期望角度之間的距離大于 0.01f,它會直接跳到期望位置并停止執行 Lerp 方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/528960.html
標籤:C#unity3d
