Search Unity

Puzzle Rotation - Reshuffle with code

Discussion in 'Scripting' started by Esestor, Aug 5, 2019.

  1. Esestor

    Esestor

    Joined:
    Mar 11, 2017
    Posts:
    3
    Hi everyone!
    I'm having an issue that I can't seem to solve on my own.

    So, task is:
    1. Have 4 2D objects with rotation at 0, 90, 180 and 270 placed on scene;

    2. Clicking on them calls Rotation:
    Code (CSharp):
    1. transform.Rotate(0f, 0f, 90f);
    of element you've clicked on.

    3. Update checks if all objects are at 0 rotation:
    Code (CSharp):
    1. if (
    2.             Mathf.Approximately(pictures[0].rotation.z, 0f) &&
    3.             Mathf.Approximately(pictures[1].rotation.z, 0f) &&
    4.             Mathf.Approximately(pictures[2].rotation.z, 0f) &&
    5.             Mathf.Approximately(pictures[3].rotation.z, 0f))
    6.            
    7.             /*
    8.             pictures[0].rotation.z == 0 &&
    9.             pictures[1].rotation.z == 0 &&
    10.             pictures[2].rotation.z == 0 &&
    11.             pictures[3].rotation.z == 0)*/
    12.         {
    13.             winText.SetActive(true);
    14.             youWin = true;
    15.         }
    Commented section seemed to work too, but switched due to advise from colleague.
    All goes well, condition is met once all objects are at 0 degrees on Z axis.

    !Problem occurs here!

    4. I'm trying to somplify level construction, so I try and reshuffle all pieces with code:
    Code (CSharp):
    1. for (int i = 0; i < pictures.Length; i++)
    2.         {
    3.             float temp = Random.Range(0, 4);
    4.             pictures[i].Rotate(0f, 0f, 90f * temp);
    5.            
    6.         }
    And, for some reason, Update if-statement doesn't recognise 0 value of all items.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Rotation is a Quaternion, which has fields x,y,z,w.

    Those values are NOT what you think they are, Euler angles along an axis. They are actually elements of a 4-element matrix, which is a Quaternion.

    If you want the Euler angles of a Quaternion, you can use the .eulerAngles field to get at them.

    HOWEVER, I caution you that there is not a one-to-one mapping from a Vector4 (in this case a Quaternion) to a Vector3 (the eulerAngles), so it might still not get you where you want.

    For such simple rotation, I suggest instead you use a separate variable for each object that is its rotation, say from 0 to 360, and keep that value in a script on that object which in turn can drive the actual Quaternion rotation of the object. Never actually query or care about the .rotation field, just drive it with your variable and then test your variable directly.