Search Unity

Rotate Character 90 Degrees

Discussion in 'Scripting' started by madelineleclair, Mar 9, 2018.

  1. madelineleclair

    madelineleclair

    Joined:
    Feb 25, 2018
    Posts:
    5
    I'm trying to make my character rotate 90 degrees each time a player presses an arrow key, but I'm having trouble with the rotation. Currently, the player moves extremely quickly between -90, 90, and 180. My code is below. if anyone can help me understand why this approach isn't working and what would be a better approach, I'd greatly appreciate it.

    Code (CSharp):
    1. public class PlayerMovement : MonoBehaviour {
    2.  
    3.     void Update()
    4.     {
    5.         float h = Input.GetAxisRaw ("Horizontal");
    6.  
    7.         if (h != 0)
    8.         {
    9.             Turn ();  
    10.         }
    11.     }
    12.  
    13.     void Turn ()
    14.     {
    15.         Vector3 angles = transform.eulerAngles;
    16.         float y = angles.y + 90;
    17.         transform.rotation = Quaternion.AngleAxis(y, Vector3.up);
    18.     }
    19. }
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Try using GetKeyDown or GetButtonDown instead of GetAxis. That will only return true for the first frame its 'down'. :)

    Also, I'd recommend that you not use euler angles that way. You can do:
    Code (csharp):
    1. transform.rotation *= Quaternion.Euler(0,90,0);
     
  3. madelineleclair

    madelineleclair

    Joined:
    Feb 25, 2018
    Posts:
    5
    Thanks so much for your help! The problem was indeed caused by the GetAxisRaw.