[英]How to rotate the 2D object in one axis with the mouse correctly
目標是在按住鼠標按鈕的同時旋轉磁盤。
以下代碼完美地完成了它的工作 - 正是我想要的:
public class Rotator : MonoBehaviour {
private void OnMouseDrag()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
difference.Normalize();
float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotation_z);
}
}
除了在不拖動的情況下正常單擊時出現的異常磁盤行為:
我怎樣才能防止這種旋轉跳躍? 我只需要拖動時平滑旋轉。
由於您只想在拖動時應用此功能,因此我會這樣做
就像是
private Vector2 startDelta;
private Quaternion startRotation;
private void OnMouseDown()
{
// Store the initial mouse offset
startDelta = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
startDelta.Normalize();
// Store the initial rotation
startRotation = transform.rotation;
}
private void OnMouseDrag()
{
// Get the current mouse offset
Vector2 currentDelta = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
currentDelta.Normalize();
// Get the angle difference between the initial and current offset
var rotation_z = Vector2.SignedAngle(startDelta, currentDelta);
// From the initial rotation rotate about the calculated difference angle
transform.rotation = startRotation * Quaternion.Euler(0f, 0f, rotation_z);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.