0
\$\begingroup\$

I want the cockpits rotation to lag behind that of the cameras, so I wrote this code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class Delay : MonoBehaviour {
    public Transform BodyRot;
    public Transform CurrentRot;
    public Vector3 changeInRot;
    public float divideRot;
    Vector3 BodyTarget;
    Vector3 CurrentInitialRot;

    // Update is called once per frame
    void Update () {
        Vector3 BodyTarget = BodyRot.rotation.eulerAngles;

        Vector3 CurrentInitialRot = CurrentRot.rotation.eulerAngles;

        changeInRot = BodyTarget -= CurrentInitialRot;



        if(CurrentInitialRot != BodyTarget)
        {
            RotateFinal();
        }

    }

    void RotateFinal()
    {
        CurrentInitialRot += changeInRot / divideRot;
        transform.rotation = Quaternion.Euler(CurrentInitialRot);
    }
}

But it glitches out frequently. (DivideRot is how many times to divide the distance between the target and current position, so that it takes time to rotate)

\$\endgroup\$
2
\$\begingroup\$

Don’t rely on eulerAngles for animating rotation. Use Quaternion.RotateTowards instead. Your divideRot also does not take frame rate into account, which can cause jittery animation.

transform.rotation = Quaternion.RotateTowards(transform.rotation, BodyRot.rotation, someSpeed * Time.deltaTime);

Where someSpeed is the speed you want to rotate in degrees per second. So try starting with 360 and adjust up or down from there.

\$\endgroup\$
  • \$\begingroup\$ Thank you, this solved the problem! I did not even know this existed..... \$\endgroup\$ – Spaceguy99 May 14 '18 at 12:01
  • \$\begingroup\$ Feel free to click the checkbox \$\endgroup\$ – Ed Marty May 14 '18 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.