Home > Net >  Why the object is not rotating towards the other object?
Why the object is not rotating towards the other object?

Time:05-24

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;
    }
}

I used a breakpoint and when startRot is true it does getting to the Quaternion.RotateTowards line in the Update and the rotationSpeed is 5 but the transform is not rotating at all.

I want that the transform will rotate by 180 degrees or what even angle the transform is looking at forward it should rotate back towards the target.

The transform and the target both facing same direction and still the transform is not rotating at all towards the target.

If i'm changing on my own the transform rotation at runtime it will rotate but when it's getting to the Update it's not rotating at all.

CodePudding user response:

Quaternion.RotateTowards will change one rotation towards another one, if two objects are facing same direction, they have same rotation, so nothing will be changed.

If you want the object to face the target, you need use a rotation created by Quaternion.LookRotation.

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