Search Unity

Move and rotate character relative to camera

Discussion in 'Scripting' started by dragonice501, Feb 14, 2016.

  1. dragonice501

    dragonice501

    Joined:
    Dec 2, 2015
    Posts:
    146
    I'm trying to make something like the system in the 3D Zelda games but can't figure out how to make the player rotate towards their move direction relative to the camera.

    This is what i currently use to make them always face forward from the camera when moving.

    Code (CSharp):
    1. void SnapAlignWithCamera()
    2.     {
    3.         if (MoveVector.x != 0 || MoveVector.z != 0)
    4.         {
    5.             transform.rotation = Quaternion.Euler (transform.rotation.eulerAngles.x, Camera.main.transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
    6.         }
    7.     }
    How can i make it to where they still move relative to the camera but face their move direction?
     
  2. Abhinav91

    Abhinav91

    Joined:
    Oct 21, 2013
    Posts:
    67
    Having a little trouble understanding this. Can you explain a little more?
     
  3. dragonice501

    dragonice501

    Joined:
    Dec 2, 2015
    Posts:
    146
    Actually i manged to find a solution to this code. What it simply did was IF the character was moving along is X or Z axis it would snap to face the forward direction of the Main Camera.

    But this code makes so it faces the direction its moving relative to it.

    Code (CSharp):
    1. public void RotateTowardsMoveDirection(Vector3 direction)
    2.     {
    3.         Vector3 cameraDirection = Camera.main.transform.rotation * direction;
    4.         Vector3 currentDirection = transform.position + cameraDirection;
    5.  
    6.         Quaternion targetRotation = Quaternion.LookRotation (currentDirection - transform.position);
    7.         Quaternion constrained = Quaternion.Euler (0, targetRotation.eulerAngles.y, 0);
    8.  
    9.         transform.rotation = Quaternion.Slerp (transform.rotation, constrained, Time.deltaTime * Smooth);
    10.  
    11.         //if (MoveVector.x != 0 || MoveVector.z != 0)
    12.             //transform.rotation = Quaternion.Euler (transform.rotation.eulerAngles.x, Camera.main.transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
    13.     }
    However, now this code makes the character move relative to the direction its facing in, not relative to the camera.
     
    Last edited: Feb 15, 2016
  4. dragonice501

    dragonice501

    Joined:
    Dec 2, 2015
    Posts:
    146
    In the order of the attached pictures, this is what the previous code did with the SnapAlignWithCamera(), what it does now with the RotateTowardsMoveDirection(), and what i want it to do.
     

    Attached Files: