Paweł Jastrzębski
Paweł Jastrzębski

Reputation: 746

Strange RotateTowards issue in Unity 3D

I am writing a simple game in Unity 3D with C# as a scripting language. I need to rotate the camera around 180 degrees. The strange thing is the first call of Quarterion.RotateTowards works, while the other one doesn't, although it should be just a reference to the same object.

public class ChangeCamera : MonoBehaviour {

Quaternion firstMinionCameraRot, secondMinionCameraRot;

Quaternion newRot; 

// Use this for initialization
void Start () {
    Quaternion firstMinionCameraRot = new Quaternion(0.0f, 1.0f, -0.3f, 0.0f);
    Quaternion secondMinionCameraRot = new Quaternion(-0.3f, 0.0f, 0.0f, -1.0f);
} 

// Update is called once per frame
void Update () {

    newRot = this.transform.rotation;

    // This one works 
    newRot = Quaternion.RotateTowards(newRot, new Quaternion(-0.3f, 0.0f, 0.0f, -1.0f), 0.05f * Time.deltaTime);
    // This one doesn't 
    newRot = Quaternion.RotateTowards(newRot, secondMinionCameraRot, 50.0f * Time.deltaTime);

    newRot = this.transform.rotation;
 }

EDIT: I am doing the final assignment newRot = this.transform.rotation; I missed this line when preparing the code snippet. When I am using the second option (where the Quaterion was initialized in the begining, no exception is being thrown, it just does not perform any rotation).

Upvotes: 0

Views: 618

Answers (1)

RCYR
RCYR

Reputation: 1492

i) You are not initializing your variables correctly. You are hiding the two variables you intend to work on.

Quaternion firstMinionCameraRot, secondMinionCameraRot;
void Start () {
    firstMinionCameraRot = new Quaternion(0.0f, 1.0f, -0.3f, 0.0f);
    secondMinionCameraRot = new Quaternion(-0.3f, 0.0f, 0.0f, -1.0f);
}

ii) As @HBomb mentionned, set your rotation back on your game object.

void Update () {
    transform.rotation = Quaternion.RotateTowards(transform.rotation, secondMinionCameraRot, 50.0f * Time.deltaTime);
 }

NOTE: Quaternion is a struct thus it is passed by value. You cannot expect to work on a reference to your game object's rotation like you appear to be doing with the "newRot" variable.

Upvotes: 2

Related Questions