Last active
April 29, 2023 12:15
-
-
Save LaserKaspar/b76ff85352118c10a0bc01d724f04737 to your computer and use it in GitHub Desktop.
(UnityEngine) Simple Physics-Based Character Controller
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 System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class PlayerController : MonoBehaviour | |
{ | |
[SerializeField] private Transform camera; | |
[SerializeField] private float velocity; | |
[SerializeField] private float acceleration; | |
[SerializeField] private float skinWidth; | |
[SerializeField] private float jumpForce; | |
[SerializeField] private float groundDrag; | |
[SerializeField] private float airDrag; | |
[SerializeField] private LayerMask groundLayerMask; | |
private Rigidbody _rigidbody; | |
[SerializeField] private bool grounded; | |
private void Awake() | |
{ | |
_rigidbody = GetComponent<Rigidbody>(); | |
} | |
void FixedUpdate() | |
{ | |
Movement(); | |
LimitVelocity(); | |
} | |
private void Update() | |
{ | |
CheckGround(); | |
} | |
private void LimitVelocity() | |
{ | |
Vector3 currentVelocity = Vector3.ProjectOnPlane(_rigidbody.velocity, Vector3.up); | |
if (currentVelocity.magnitude > velocity) | |
{ | |
Vector3 limitVel = currentVelocity.normalized * velocity; | |
limitVel.y = _rigidbody.velocity.y; | |
_rigidbody.velocity = limitVel; | |
} | |
} | |
void Movement() | |
{ | |
Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) * velocity; | |
Vector3 movement = camera.TransformDirection(input); | |
movement = Vector3.ProjectOnPlane(movement, Vector3.up).normalized * input.magnitude; | |
_rigidbody.AddForce(movement * acceleration * velocity, ForceMode.Force); | |
} | |
void CheckGround() | |
{ | |
grounded = GroundCheck(); | |
_rigidbody.drag = grounded ? groundDrag : airDrag; | |
if (grounded && Input.GetKeyDown(KeyCode.Space)) | |
{ | |
Jump(); | |
} | |
} | |
void Jump() | |
{ | |
_rigidbody.AddForce(Vector3.up * jumpForce); | |
} | |
bool GroundCheck() | |
{ | |
RaycastHit rhit; | |
Physics.Raycast(transform.position, -Vector3.up, out rhit, 1f + skinWidth, groundLayerMask); | |
return rhit.collider; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment