private float rotationZ;
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
difference.Normalize();
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotationZ);
到目前為止,我的代碼將獲取游標位置并立即執行轉換。但是,如果我將游標移動到樞軸中心附近,旋轉將是瞬時且斷斷續續的。我怎樣才能對此添加輕微的平滑,使其從 A 點到 B 點的移動速度更慢?
uj5u.com熱心網友回復:
您將實際目標值存盤在一個欄位中,然后朝著它移動
private Quaternion targetRotation;
private Camera camera;
private void Awake ()
{
// Camera.main is quite expensive so rather store the reference
camera = Camera.main;
// Initially set your current rotation as target
// especially important if you don't always update the target rotation but e.g.
// only if a certain button is pressed
targetRotation = transform.rotation;
}
private void Update ()
{
UpdateTargetRotation();
RotateTowardsTarget();
}
private void UpdateTargetRotation ()
{
var difference = (camera.ScreenToWorldPoint(Input.mousePosition) - transform.position).normalized;
var targetRotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
targetRotation = Quaternion.Euler(0, 0, targetRotationZ);
}
現在RotateTowardsTarget你有很多選擇。
其中之一確實會使用Quaternion.Lerp某個插值因子。在這里,您可以平滑地向目標值進行插值,但在開始時非常快,并且無論您總共旋轉多少,越接近目標值就會變得越來越慢。這也可能永遠不會真正達到確切的目標值。
// Adjust in the Inspector
public float interpolationFactor = 5f;
private void RotateTowardsTarget ()
{
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, interpolationFactor * Time.deltaTime);
}
或者另一種選擇是寧愿使用Quaternion.RotateTowards以固定速度旋轉的
// Adjust in the Inspector
public float anglePerSecond = 45;
private void RotateTowardsTarget ()
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, anglePerSecond * Time.deltaTime);
}
uj5u.com熱心網友回復:
您正在尋找 Mathf.Lerp
如何使用它的示例:
float rotationZ;
//Changes how quickly will rotate
const float rotationSpeed = 0.58f;
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
difference.Normalize();
rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
float lerpRotation = Mathf.Lerp(transform.rotation.z, rotationZ, Time.deltaTime * rotationSpeed);
transform.rotation = Quaternion.Euler(0f, 0f, lerpRotation);
uj5u.com熱心網友回復:
您應該在協程中使用 Quaternion.Slerp()。您檢查每個 FixedUpdate 的游標位置,然后啟動一個協程,該協程在每一幀內插值并設定旋轉,直到下一個 FixedUpdate 到來。產生的滯后基本上是不明顯的,看起來如絲般光滑。
對于插值 t 值,您應該使用一個變數來存盤自上次 FixedUpdate 以來經過的時間(您從 time.deltatimes 將其相加),并獲得 t,您只需將其除以 0.02 秒。
然后當協程完成時,將旋轉設定為最終值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362088.html
