簡體   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