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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Rotate gameobject to a specific rotation

Discussion in 'Scripting' started by cyboerg, May 16, 2015.

  1. cyboerg

    cyboerg

    Joined:
    Jan 28, 2015
    Posts:
    9
    Hey People!

    Im trying to make the controlls for a game. The controlls are wsad.
    When W is pressed the gameobject needs to rotate to -90 on the Yaxis.
    When S is pressed the game object neeneeds to rotate to 90 on the Yaxis.
    D needs to rotate the gameobject to 0 on the Yaxis
    and A to 180 int the Yaxis.

    My current code rotates the gameobject BY -90, 90,180
    So if its at -90 and I press S it rotates BY 90 and is looking in the wrong direction.

    How do I code it to have it rotate to -90, 90, 0 and 180 instead of rotating it by -90,90,0 and 180.
     
  2. SnakeTheRipper

    SnakeTheRipper

    Joined:
    Dec 31, 2014
    Posts:
    136
    It's hard to understand what you mean.
    1. You want the object to look at 0, 90, 180, 270 degrees depending on what you press.
    2. You want the object to rotate your object by 90 or -90 depending on what you press.
    ?
     
  3. cyboerg

    cyboerg

    Joined:
    Jan 28, 2015
    Posts:
    9
    I want it to look at 0, 90,180,270 depending on what I press.

    sorry about that...
     
  4. SnakeTheRipper

    SnakeTheRipper

    Joined:
    Dec 31, 2014
    Posts:
    136
    Easy then.

    It should look something like this :

    Code (CSharp):
    1.     private void Update()
    2.     {
    3.         if (Input.GetKey(KeyCode.W))
    4.         {
    5.             gameObject.transform.localEulerAngles = new Vector3(0, 0, 0);
    6.         }
    7.         else if (Input.GetKey(KeyCode.S))
    8.         {
    9.             gameObject.transform.localEulerAngles = new Vector3(0, 90, 0);
    10.         }
    11.         else if (Input.GetKey(KeyCode.A))
    12.         {
    13.             gameObject.transform.localEulerAngles = new Vector3(0, 180, 0);
    14.         }
    15.         else if (Input.GetKey(KeyCode.D))
    16.         {
    17.             gameObject.transform.localEulerAngles = new Vector3(0, 270, 0);
    18.         }
    19.     }
     
    matmatBeck likes this.