繁体   English   中英

线性旋转二维 object

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM