首页 > 解决方案 > 线性旋转 2D 对象

问题描述

我的 2D 对象正在查找 ( transform.up = (0,1))。

当我单击屏幕中的某个位置时,我希望对象查看我单击的位置。我还希望它线性旋转:它应该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.deltaTime180 / Mathf.Max(1, Mathf.Abs(angle)),它表示角度越大,旋转所需的时间越长,但我不知道我是否做得对(它有效)或者这是否是更好的方法.

标签: c#unity3dgeometry

解决方案


定义一些rotationSpeed字段:

public float rotationSpeed = 90f;

用于Quaternion.LookRotation获取Quaternion您想要旋转的方向。您希望本地前向指向全局前向,本地向上指向目标位置,因此使用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);
    }
}

推荐阅读