Search Unity

Camera relative movement

Discussion in 'Scripting' started by taylonwolfsong, Jul 25, 2011.

  1. taylonwolfsong

    taylonwolfsong

    Joined:
    May 15, 2011
    Posts:
    2
    I've been looking over the various threads here and elsewhere trying to find help with what I need, so figured I would try posting it.

    I'm trying to develop an action rpg, but having some difficulty with the controls. I'm developing it for use with a gamepad, and trying to set it up so the character movement controls are relative to the camera. That is, if you are facing the camera, you have to press down to move forward, or if you are facing to the right of the camera, you need to press right. I've tried using camera.main.transform.TransformDirection, but that gets wonky if the camera is moving. Additionally, it doesnt make the controls relative, it makes the movement relative. (IE. Character is facing to the right of the character, and i press up on the movement stick, the character moves right).

    Any help would be appreciated
     
  2. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    you are actually describing two seperate events. First... You press right... So you want your character to move....

    player.transform.Translate(Camera.transform.right)

    Then... you want him to face right....

    player.transform.LookAt(player.transform.position + Camera.transform.right)

    This all is simplified by gathering the axis of the movement..
    Code (csharp):
    1.  
    2. var speed=5.0;
    3. var move=Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    4. player.transform.Translate(Camera.transform.TransformDirection(move) * speed * Time.deltaTime);
    5. player.transform.LookAt(player.transform.position + Camera.transform.TransformDirection(move));
    6.  
    Or something like that.. (of course it will need to be debugged. )