Created
October 25, 2020 02:20
-
-
Save Kyonru/759b71e78b7a18a823d138becf50c24b to your computer and use it in GitHub Desktop.
Character Contoller
This file contains 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 PlayerMovement : MonoBehaviour | |
{ | |
[SerializeField] private float speed = 10f; | |
[SerializeField] private float jumpHeight = 10f; | |
[SerializeField] private float gravity = -9.81f; | |
[SerializeField] private float groundDistance = 0.4f; | |
[SerializeField] private float runSpeed = 20f; | |
[SerializeField] private Transform groundCheck; | |
[SerializeField] private LayerMask groundLayer; | |
private Vector3 _velocity; | |
private CharacterController _controller; | |
private bool _isGrounded; | |
private void Start() | |
{ | |
_controller = GetComponent<CharacterController>(); | |
} | |
private void Update() | |
{ | |
_isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundLayer); | |
if (_isGrounded && _velocity.y < 0) | |
{ | |
_velocity.y = -2f; | |
} | |
var x = Input.GetAxis("Horizontal"); | |
var z = Input.GetAxis("Vertical"); | |
var transform1 = transform; | |
var move = (transform1.right * x) + (transform1.forward * z); | |
var currentSpeed = Input.GetButton("Run") ? runSpeed : speed; | |
_controller.Move(move * (currentSpeed * Time.deltaTime)); | |
if (Input.GetButtonDown("Jump") && _isGrounded) | |
{ | |
_velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity); | |
} | |
_velocity.y += gravity * Time.deltaTime; | |
_controller.Move(_velocity * Time.deltaTime); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment