Search Unity

Move and rotate 3rd person character relative to a Transform

Discussion in 'Scripting' started by thommyboy02, Jun 17, 2019.

  1. thommyboy02

    thommyboy02

    Joined:
    Aug 18, 2017
    Posts:
    7
    I'm trying to code movement for a third person character in VR and I want the movement and rotation of the character to be relative to the Camera's position. The Camera's position will change throughout the level based on the player reaching checkpoints and the Camera being re-positioned to a new transform. I want the character to move relative to the current position of the Camera at all times. I've had a look for solutions and can't seem to find one that works. My player still moves relative to world space rather than the camera. Any ideas where I'm going wrong?

    Code (CSharp):
    1.  
    2. Vector3 movement;
    3.  
    4. void FixedUpdate()
    5.     {
    6.         float turn = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick).x;
    7.         float move = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick).y;
    8.  
    9.         Move(turn, move);
    10.     }
    11.  
    12. void Move(float turn, float move)
    13.     {
    14.         movement.Set(turn, 0f, move);
    15.         movement = m_Cam.transform.TransformDirection(movement);
    16.         movement.y = 0f;
    17.         movement = movement.normalized * speed * Time.deltaTime;
    18.         rb.MovePosition(transform.position + movement);
    19.  
    20.         Quaternion targetRotation = Quaternion.LookRotation(movement, Vector3.up);
    21.         Quaternion newRotation = Quaternion.Lerp(transform.rotation, targetRotation, turnSmoothing * Time.deltaTime);
    22.         rb.MoveRotation(newRotation);
    23.     }