繁体   English   中英

为什么物体没有朝着另一个物体旋转?

[英]Why the object is not rotating towards the other object?

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.Characters.ThirdPerson;

public class DistanceCheck : MonoBehaviour
{
    public Transform target;
    public float lerpDuration;
    public float rotationSpeed;
    public GameObject descriptionTextImage;
    public TextMeshProUGUI text;
    public ThirdPersonUserControl thirdPersonusercontrol;

    private Animator anim;
    private float timeElapsed = 0;
    private float startValue = 1;
    private float endValue = 0;
    private float valueToLerp = 0;
    private bool startRot = false;

    // Start is called before the first frame update
    void Start()
    {
        anim = transform.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if(startRot)
        {
            transform.rotation = Quaternion.RotateTowards(transform.rotation,
                target.rotation, rotationSpeed * Time.deltaTime);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "Colliding Area")
        {
            StartCoroutine(SlowDown());
        }
    }

    IEnumerator SlowDown()
    {
        while (timeElapsed < lerpDuration)
        {
            valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
            anim.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;

            yield return null;
        }

        thirdPersonusercontrol.enabled = false;
        descriptionTextImage.SetActive(true);

        yield return new WaitForSeconds(3f);

        startRot = true;
    }
}

我使用了一个断点,当 startRot 为 true 时,它​​会到达 Update 中的 Quaternion.RotateTowards 行,rotationSpeed 为 5,但变换根本不旋转。

我希望变换将旋转 180 度,或者变换向前看的均匀角度应该旋转回目标。

变换和目标都面向相同的方向,但变换仍然没有向目标旋转。

如果我在运行时自行更改变换旋转,它会旋转,但是当它到达更新时,它根本不会旋转。

Quaternion.RotateTowards将一个旋转改变为另一个旋转,如果两个对象面向相同的方向,它们具有相同的旋转,所以什么都不会改变。

如果您希望对象面向目标,则需要使用Quaternion.LookRotation创建的旋转。

transform.rotation = Quaternion.RotateTowards(transform.rotation, 
    Quaternion.LookRotation(target.position - transform.position),
    rotationSpeed * Time.deltaTime);

暂无
暂无

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

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