Search Unity

Movement direction and camera.

Discussion in 'Scripting' started by Kryber, Mar 10, 2014.

  1. Kryber

    Kryber

    Joined:
    Apr 14, 2013
    Posts:
    92
    Hi. How can I make sure that the direction of motion is equal to the direction in which I'm looking at the camera? :)

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class PlayerMovement : MonoBehaviour {
    5.  
    6.     public Transform camera;
    7.     public float speed;
    8.     public float jumpHeight;
    9.     public float gravity;
    10.  
    11.     private CharacterController controller;
    12.     private Vector3 moveDirection = Vector3.zero;
    13.  
    14.    
    15.     void Start()
    16.     {
    17.         controller = gameObject.GetComponent<CharacterController>();
    18.     }
    19.  
    20.     void Update()
    21.     {
    22.         if(controller.isGrounded)
    23.         {
    24.             moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    25.             moveDirection = transform.TransformDirection(moveDirection);
    26.             moveDirection *= speed;
    27.  
    28.             if(Input.GetButtonDown("Jump"))
    29.             {
    30.                 moveDirection.y = jumpHeight;
    31.             }
    32.         }
    33.  
    34.         moveDirection.y -= gravity * Time.deltaTime;
    35.  
    36.         controller.Move(moveDirection * Time.deltaTime);
    37.     }
    38. }
    39.