简体   繁体   English

如何缓慢地将字符旋转到相反的方向?

[英]How to rotate character to the opposite direction smooth slowly?

private void Update()
{
    Quaternion newRotation = Quaternion.AngleAxis(180, Vector3.up);
    transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, .05f);
}

The problem it's not always rotating by 180. I control the character movement and rotation and at some point i want the character to rotate to the opposite direction no matter what direction he is facing now.问题并不总是旋转 180。我控制角色的移动和旋转,并且在某些时候我希望角色旋转到相反的方向,无论他现在面对什么方向。

If Y on the rotation is 120 or 45 or 4 or 23 always rotate to the opposite direction.如果 Y 上的旋转是 120 或 45 或 4 或 23 总是向相反的方向旋转。

To solve this problem you need an IEnumerator that maintains the original angle and changes it over time, keep in mind that Point to point changes can never be defined directly in Update or you will have to use a hypothetical variable in Consider the body of the class, which is not recommended.要解决这个问题,您需要一个IEnumerator来保持原始角度并随着时间的推移对其进行更改,请记住,点对点的更改永远不能直接在 Update 中定义,否则您将不得不在考虑类的主体中使用假设变量,不推荐。

public IEnumerator DoRotate(float time)
{
    var newRotation = Quaternion.AngleAxis(180, Vector3.up) * transform.rotation;

    var baseRotation = transform.rotation;

    var progress = 0f;

    while (progress < 1)
    {
        progress += Time.deltaTime / time;

        transform.rotation = Quaternion.Lerp(baseRotation, newRotation, progress);

        yield return new WaitForEndOfFrame();
    }
}

After defining IEnumerator , it is enough to start it only once, where it is needed, as below, and the character will rotate at the defined time.定义IEnumerator后,只需在需要的地方启动一次就足够了,如下所示,角色将在定义的时间旋转。

public void Start() => StartCoroutine(DoRotate(2f)); // rotate over 2 seconds

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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