Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

character unable to move relative to the camera

Discussion in 'Getting Started' started by jermainetai0307, Nov 9, 2023.

  1. jermainetai0307

    jermainetai0307

    Joined:
    Nov 10, 2022
    Posts:
    27
    Hi, i followed a tutorial on how to use camera-relative movement.

    the code is here:
    Code (CSharp):
    1. void MovePlayerRelativeToCamera()
    2.     {
    3.         float VerticalInput = Input.GetAxis("Vertical");
    4.         float HorizontalInput = Input.GetAxis("Horizontal");
    5.  
    6.         Vector3 forward = Camera.main.transform.forward;
    7.         Vector3 right = Camera.main.transform.right;
    8.         forward.y = 0;
    9.         right.y = 0;
    10.         forward = forward.normalized;
    11.         right = right.normalized;
    12.  
    13.         Vector3 forwardRelativeVerticalInput = VerticalInput * forward;
    14.         Vector3 rightRelativeHorizontalInput = HorizontalInput * right;
    15.  
    16.         Vector3 cameraRelativeMovement = forwardRelativeVerticalInput + rightRelativeHorizontalInput;
    17.         transform.Translate(cameraRelativeMovement, Space.World);
    18.     }
    I think i understand the code well enough, however when i start the game. my player does not move at all.
    I am assuming Camera.main refers to the default "Main Camera" object. And i also use the cinemachine Freelook camera, so i am not sure if cinemachine's freelook camera is interfering with this.