[英]Rotate 2D object linearly
我的 2D object 正在查找( transform.up = (0,1)
)。
當我單擊屏幕中的某個位置時,我希望 object 能夠查看我單擊的位置。 我還希望它線性旋轉:它應該每秒旋轉d
度,這意味着旋轉兩倍的角度需要兩倍的時間。
這是我的代碼:
void Update() {
if (Input.GetMouseButtonDown(0)) {
Vector2 wPos = cameraRef.ScreenToWorldPoint(Input.mousePosition);
StartCoroutine(LookAt(mouseScreenPosition));
}
}
public IEnumerator LookAt(Vector2 position) {
Vector2 direction = (position - (Vector2) transform.position).normalized;
float angle = Vector2.SignedAngle(direction, transform.up);
float startAngle = transform.eulerAngles.z;
for(float t = 0; t <= 1; t += Time.deltaTime * (180 / Mathf.Max(1, Mathf.Abs(angle)))) {
transform.eulerAngles = new Vector3(0, 0, Mathf.Lerp(startAngle, startAngle - angle, t));
yield return null;
}
}
我乘以Time.deltaTime
的因子是180 / Mathf.Max(1, Mathf.Abs(angle))
,這表示角度越大,旋轉所需的時間就越長,但我不知道我是否'我做對了(它有效),或者如果這是更好的方法。
定義一些rotationSpeed
字段:
public float rotationSpeed = 90f;
使用Quaternion.LookRotation
獲取要旋轉的Quaternion
。 您希望本地前向指向全局前向方向,本地向上指向目標 position,因此使用Quaternion.LookRotation(Vector3.forward,targetDirection)
:
public IEnumerator LookAt(Vector2 position) {
// casting to Vector2 and normalizing is redundant
Vector3 targetDirection = position - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, targetDirection);
然后使用Quaternion.RotateTowards
與您想要在該幀中旋轉的最大度數,直到您完成向目標旋轉方向旋轉:
while (Quaternion.Angle(targetRotation, transform.rotation) > 0.01)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation,
time.deltaTime * rotationSpeed);
}
共:
public float rotationSpeed = 90f;
public IEnumerator LookAt(Vector2 position) {
// casting to Vector2 and normalizing is redundant
Vector3 targetDirection = position - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, targetDirection);
while (Quaternion.Angle(targetRotation, transform.rotation) > 0.01)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation,
time.deltaTime * rotationSpeed);
}
}
您可以使用 Quaternion.Lerp: https://docs.unity3d.com/ScriptReference/Quaternion.Lerp.html
我想這就是你要找的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.