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

Changing Prefab Direction

Discussion in 'Scripting' started by Fersutagames_, Nov 18, 2015.

  1. Fersutagames_

    Fersutagames_

    Joined:
    May 2, 2013
    Posts:
    52
    Hey Awesome Forum Members!

    (I think i have coders grammar at the moment so excuse capitals if they're in the wrong spot :p)

    I'm a little bit stuck at the moment to which methods will allow me to change just the direction the prefab is facing, it's a game similar to that zig zag game, and i have all the mechanics working, and the game looking sweet! Just my character is always facing the same way..

    here's my movement code that changes the players direction when you click the mouse;
    Code (JavaScript):
    1.       if (Input.GetMouseButtonDown(0) && !isDead)
    2.         {
    3.             playing = true;
    4.             score++;
    5.             scoreText.text = score.ToString();
    6.  
    7.             //Switches the players direction every time we click ont he screen or mouse
    8.             if (dir == Vector3.forward)
    9.             {
    10.                 dir = Vector3.left;
    11.             }
    12.             else
    13.             {
    14.                 dir = Vector3.forward;
    15.             }
    16.         }
    17.  
    18.         //Calculates the player's movement
    19.         float amoutToMove = speed * Time.deltaTime;
    20.  
    21.         //Makes the player move
    22.         transform.Translate(dir * amoutToMove);
    23.     }
    Cheers guys! if you can help me out, you rock :D
     
  2. IroncladEarl

    IroncladEarl

    Joined:
    Jul 3, 2013
    Posts:
    87
    If the direction you want to rotate is known then you can change it using Euler angles:
    Code (CSharp):
    1. // Rotate 90 degrees only on the y axis
    2. Quaternion rot = transform.rotation;
    3. transform.rotation = Quaternion.Euler(rot.x, 90, rot.z)
    4.  
    5. // up = 0 | right = 90 | down = 180 | left = 270
    If you need a dynamic rotation where you want to rotate towards the spot where you clicked, the code will be very different. It depends what you want to do.
     
  3. Fersutagames_

    Fersutagames_

    Joined:
    May 2, 2013
    Posts:
    52
    Cheers @Saladon i'll take a look into it!