Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Code is not working properly

Discussion in 'Scripting' started by EvilRhinoGaming, Apr 13, 2021.

  1. EvilRhinoGaming

    EvilRhinoGaming

    Joined:
    Mar 31, 2021
    Posts:
    4
    What I'm having trouble with is at the bottom of the update function, it doesn't work, like nothing happens, if I take out the check for the Y Rotation it works, but I only want this to happen when the player is looking in that specific direction, I have double checked that when I'm trying to press space the player is exactly -90 on the Y Rotation.
    I have provided the entire script.
    Code (CSharp):
    1. public class OfficeCameraMovement : MonoBehaviour
    2. {
    3.     public float smooth = 1f;
    4.     private Quaternion targetRotation;
    5.     public bool isInCenter = true;
    6.  
    7.     public Animator anim;
    8.     // Start is called before the first frame update
    9.     void Start()
    10.     {
    11.         targetRotation = transform.rotation;
    12.         anim.enabled = false;
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         if (Input.GetKeyDown(KeyCode.A) && isInCenter)
    19.         {
    20.             targetRotation *= Quaternion.AngleAxis(-90, Vector3.up);
    21.         }
    22.         if (Input.GetKeyDown(KeyCode.D) && isInCenter)
    23.         {
    24.             targetRotation *= Quaternion.AngleAxis(90, Vector3.up);
    25.         }
    26.         transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 10 * smooth * Time.deltaTime);
    27.  
    28.         if(transform.rotation.y == -90 && Input.GetKeyDown(KeyCode.Space))
    29.         {
    30.             anim.enabled = true;
    31.             anim.Play("FuseBox");
    32.         }
    33.     }
    34. }
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    few problems

    first - transform.rotation is a quaternion, you're thinking of it in euler angles (you can say transform.rotation.euler)

    second - don't do float comparison like this, 89.999... or 90.00...001 won't be accepted, you can use Mathf.Approximately or do something like this:
    Code (CSharp):
    1. if ( Mathf.Abs( y - 90f ) < .01f)
     
  3. EvilRhinoGaming

    EvilRhinoGaming

    Joined:
    Mar 31, 2021
    Posts:
    4
    Thanks! It Worked! :)