Last active
October 19, 2021 12:09
-
-
Save RoeiRubach/315a523071589b5bb8366a75d537667d to your computer and use it in GitHub Desktop.
[Character Movement] Basic character movement using Unity's CharacterController component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| public class CharacterMovement | |
| { | |
| private const float JUMP_HEIGHT = 8f; | |
| private const float GRAVITY_VALUE = 9.81f; | |
| private readonly float _speed; | |
| private float _turnSmoothVelocity; | |
| private readonly Transform _target; | |
| private Vector3 _characterElevation; | |
| private readonly CharacterController _controller; | |
| public CharacterMovement(float speed, CharacterController controller) | |
| { | |
| _speed = speed; | |
| _controller = controller; | |
| _target = controller.GetComponent<Transform>(); | |
| } | |
| public void Move() | |
| { | |
| HandleGroundMovement(); | |
| HandleJump(); | |
| } | |
| private void HandleGroundMovement() | |
| { | |
| Vector3 direction = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized; | |
| HandleRotation(direction, out Vector3 moveDirection); | |
| Vector3 velocity = moveDirection.normalized * _speed; | |
| _controller.Move(velocity * Time.deltaTime); | |
| } | |
| private void HandleRotation(Vector3 direction, out Vector3 moveDirection) | |
| { | |
| if (direction == Vector3.zero) | |
| { | |
| moveDirection = default; | |
| return; | |
| } | |
| float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + Camera.main.transform.eulerAngles.y; | |
| float SmoothFacingAngle = Mathf.SmoothDampAngle(_target.eulerAngles.y, targetAngle, ref _turnSmoothVelocity, smoothTime: .1f); | |
| _target.rotation = Quaternion.Euler(0, SmoothFacingAngle, 0); | |
| moveDirection = Quaternion.Euler(0, targetAngle, 0) * Vector3.forward; | |
| } | |
| private void HandleJump() | |
| { | |
| if (IsGrounded() && _characterElevation.y < 0) | |
| _characterElevation.y = 0f; | |
| if (Input.GetButtonDown("Jump") && IsGrounded()) _characterElevation.y += Mathf.Sqrt(JUMP_HEIGHT * GRAVITY_VALUE); | |
| _characterElevation.y -= GRAVITY_VALUE * Time.deltaTime; | |
| _controller.Move(_characterElevation * Time.deltaTime); | |
| } | |
| private bool IsGrounded() | |
| { | |
| //Create a layer mask and pass it as a parameter | |
| return (Physics.Raycast(_target.position, _target.TransformDirection(Vector3.down), maxDistance: .2f, )); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment