Search Unity

Player Rotate Towards Camera Direction

Discussion in 'Scripting' started by Galactic_CakeYT, Oct 10, 2020.

  1. Galactic_CakeYT

    Galactic_CakeYT

    Joined:
    Apr 28, 2020
    Posts:
    65
    In my game my player moves around in a Space Station. Real Space Stations people move around with their arms and legs. I got my player to not get stuck in corners and stuff, by using SphereCast. But now I need to rotate my player in the direction my camera is facing. I have read previous articles and tried their, but it was buggy for me. If someone could help and explain to me what to do then thanks.

    Also I am currently using Unity's Standard Asset pack, the Rigidbody First Person Player Controller. Here is the code if you need it, but I didn't write this and most of it doesn't make sense to me either.

    Code (CSharp):
    1. [RequireComponent(typeof (Rigidbody))]
    2.     [RequireComponent(typeof (MeshCollider))]
    3.     public class RigidbodyFirstPersonController : MonoBehaviour
    4.     {
    5.         [Serializable]
    6.         public class MovementSettings
    7.         {
    8.             public float ForwardSpeed = 8.0f;   // Speed when walking forward
    9.             public float BackwardSpeed = 4.0f;  // Speed when walking backwards
    10.             public float StrafeSpeed = 4.0f;    // Speed when walking sideways
    11.             public float RunMultiplier = 2.0f;   // Speed when sprinting
    12.             public KeyCode RunKey = KeyCode.LeftShift;
    13.             public float JumpForce = 30f;
    14.             public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
    15.             [HideInInspector] public float CurrentTargetSpeed = 8f;
    16.  
    17. #if !MOBILE_INPUT
    18.             private bool m_Running;
    19. #endif
    20.  
    21.             public void UpdateDesiredTargetSpeed(Vector2 input)
    22.             {
    23.                 if (input == Vector2.zero) return;
    24.                 if (input.x > 0 || input.x < 0)
    25.                 {
    26.                     //strafe
    27.                     CurrentTargetSpeed = StrafeSpeed;
    28.                 }
    29.                 if (input.y < 0)
    30.                 {
    31.                     //backwards
    32.                     CurrentTargetSpeed = BackwardSpeed;
    33.                 }
    34.                 if (input.y > 0)
    35.                 {
    36.                     //forwards
    37.                     //handled last as if strafing and moving forward at the same time forwards speed should take precedence
    38.                     CurrentTargetSpeed = ForwardSpeed;
    39.                 }
    40. #if !MOBILE_INPUT
    41.                 if (Input.GetKey(RunKey))
    42.                 {
    43.                     CurrentTargetSpeed *= RunMultiplier;
    44.                     m_Running = true;
    45.                 }
    46.                 else
    47.                 {
    48.                     m_Running = false;
    49.                 }
    50. #endif
    51.             }
    52.  
    53. #if !MOBILE_INPUT
    54.             public bool Running
    55.             {
    56.                 get { return m_Running; }
    57.             }
    58. #endif
    59.         }
    60.  
    61.  
    62.         [Serializable]
    63.         public class AdvancedSettings
    64.         {
    65.             public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
    66.             public float stickToGroundHelperDistance = 0.5f; // stops the character
    67.             public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
    68.             public bool airControl; // can the user control the direction that is being moved in the air
    69.             [Tooltip("set it to 0.1 or more if you get stuck in wall")]
    70.             public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
    71.         }
    72.  
    73.  
    74.         public Camera cam;
    75.         public MovementSettings movementSettings = new MovementSettings();
    76.         public MouseLook mouseLook = new MouseLook();
    77.         public AdvancedSettings advancedSettings = new AdvancedSettings();
    78.  
    79.  
    80.         private Rigidbody m_RigidBody;
    81.         private CapsuleCollider m_Capsule;
    82.         private float m_YRotation;
    83.         private Vector3 m_GroundContactNormal;
    84.         private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;
    85.  
    86.  
    87.         public Vector3 Velocity
    88.         {
    89.             get { return m_RigidBody.velocity; }
    90.         }
    91.  
    92.         public bool Grounded
    93.         {
    94.             get { return m_IsGrounded; }
    95.         }
    96.  
    97.         public bool Jumping
    98.         {
    99.             get { return m_Jumping; }
    100.         }
    101.  
    102.         public bool Running
    103.         {
    104.             get
    105.             {
    106. #if !MOBILE_INPUT
    107.                 return movementSettings.Running;
    108. #else
    109.                 return false;
    110. #endif
    111.             }
    112.         }
    113.  
    114.  
    115.         private void Start()
    116.         {
    117.             m_RigidBody = GetComponent<Rigidbody>();
    118.             m_Capsule = GetComponent<CapsuleCollider>();
    119.             mouseLook.Init (transform, cam.transform);
    120.         }
    121.  
    122.  
    123.         private void Update()
    124.         {
    125.             RotateView();
    126.  
    127.             if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump)
    128.             {
    129.                 m_Jump = true;
    130.             }
    131.         }
    132.  
    133.  
    134.         private void FixedUpdate()
    135.         {
    136.             GroundCheck();
    137.             Vector2 input = GetInput();
    138.  
    139.             if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
    140.             {
    141.                 // always move along the camera forward as it is the direction that it being aimed at
    142.                 Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x;
    143.                 desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
    144.  
    145.                 desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed;
    146.                 desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed;
    147.                 desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed;
    148.                 if (m_RigidBody.velocity.sqrMagnitude <
    149.                     (movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed))
    150.                 {
    151.                     m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse);
    152.                 }
    153.             }
    154.  
    155.             if (m_IsGrounded)
    156.             {
    157.                 m_RigidBody.drag = 5f;
    158.  
    159.                 if (m_Jump)
    160.                 {
    161.                     m_RigidBody.drag = 0f;
    162.                     m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
    163.                     m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
    164.                     m_Jumping = true;
    165.                 }
    166.  
    167.                 if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
    168.                 {
    169.                     m_RigidBody.Sleep();
    170.                 }
    171.             }
    172.             else
    173.             {
    174.                 m_RigidBody.drag = 0f;
    175.                 if (m_PreviouslyGrounded && !m_Jumping)
    176.                 {
    177.                     StickToGroundHelper();
    178.                 }
    179.             }
    180.             m_Jump = false;
    181.         }
    182.  
    183.  
    184.         private float SlopeMultiplier()
    185.         {
    186.             float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
    187.             return movementSettings.SlopeCurveModifier.Evaluate(angle);
    188.         }
    189.  
    190.  
    191.         private void StickToGroundHelper()
    192.         {
    193.             RaycastHit hitInfo;
    194.             if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
    195.                                    ((m_Capsule.height/2f) - m_Capsule.radius) +
    196.                                    advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
    197.             {
    198.                 if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
    199.                 {
    200.                     m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
    201.                 }
    202.             }
    203.         }
    204.  
    205.  
    206.         private Vector2 GetInput()
    207.         {
    208.          
    209.             Vector2 input = new Vector2
    210.                 {
    211.                     x = CrossPlatformInputManager.GetAxis("Horizontal"),
    212.                     y = CrossPlatformInputManager.GetAxis("Vertical")
    213.                 };
    214.             movementSettings.UpdateDesiredTargetSpeed(input);
    215.             return input;
    216.         }
    217.  
    218.  
    219.         private void RotateView()
    220.         {
    221.             //avoids the mouse looking if the game is effectively paused
    222.             if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;
    223.  
    224.             // get the rotation before it's changed
    225.             float oldYRotation = transform.eulerAngles.y;
    226.  
    227.             mouseLook.LookRotation (transform, cam.transform);
    228.  
    229.             if (m_IsGrounded || advancedSettings.airControl)
    230.             {
    231.                 // Rotate the rigidbody velocity to match the new direction that the character is looking
    232.                 Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
    233.                 m_RigidBody.velocity = velRotation*m_RigidBody.velocity;
    234.             }
    235.         }
    236.  
    237.         /// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
    238.         private void GroundCheck()
    239.         {
    240.             m_PreviouslyGrounded = m_IsGrounded;
    241.             RaycastHit hitInfo;
    242.             if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
    243.                                    ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
    244.             {
    245.                 m_IsGrounded = true;
    246.                 m_GroundContactNormal = hitInfo.normal;
    247.             }
    248.             else
    249.             {
    250.                 m_IsGrounded = false;
    251.                 m_GroundContactNormal = Vector3.up;
    252.             }
    253.             if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
    254.             {
    255.                 m_Jumping = false;
    256.             }
    257.         }
    258.     }