using UnityEngine;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
///
/// Simple first/third-person style character controller driven by a
/// : WASD for horizontal movement and Space to jump.
///
/// Movement can be camera-relative (W moves away from the camera) so it feels
/// natural with the fixed scene camera. Gravity and jumping are integrated
/// manually because CharacterController does not apply physics on its own.
///
/// The script reads input through the new Input System (Keyboard.current) when it
/// is enabled, and falls back to the legacy Input Manager otherwise. The project
/// currently runs the new Input System only.
///
/// Attach this to the Player GameObject (the one that owns the CharacterController).
///
/// Note: the class is intentionally named PlayerCharacterController to avoid a
/// name clash with Unity.VisualScripting's example "PlayerController" type.
///
[RequireComponent(typeof(CharacterController))]
[DisallowMultipleComponent]
public class PlayerCharacterController : MonoBehaviour
{
[Header("Movement")]
[Tooltip("Horizontal movement speed in units per second.")]
public float moveSpeed = 4f;
[Tooltip("If ON, WASD is interpreted relative to the camera (W = away from " +
"the camera). If OFF, WASD moves along the world X/Z axes.")]
public bool cameraRelative = true;
[Tooltip("Camera used for camera-relative movement. Empty = Camera.main.")]
public Transform cameraTransform;
[Header("Rotation")]
[Tooltip("If ON, the character smoothly turns to face its movement direction.")]
public bool rotateTowardMovement = true;
[Tooltip("Turn speed in degrees per second (used when 'Rotate Toward Movement' is on).")]
public float rotationSpeed = 720f;
[Header("Jump & Gravity")]
[Tooltip("Peak jump height in units.")]
public float jumpHeight = 1.2f;
[Tooltip("Gravity in units per second squared (negative = downward).")]
public float gravity = -19.62f;
[Tooltip("Small downward velocity kept while grounded so the controller " +
"stays firmly on the ground (and isGrounded stays reliable).")]
public float groundedStickVelocity = -2f;
[Header("Slope Sliding")]
[Tooltip("If ON, the character slides down surfaces steeper than the " +
"CharacterController's Slope Limit (and off sharp edges/corners) " +
"instead of balancing on them.")]
public bool slideDownSteepSlopes = true;
[Tooltip("How quickly the slide accelerates while on a too-steep surface " +
"(units per second squared).")]
public float slideAcceleration = 20f;
[Tooltip("Maximum downhill slide speed (units per second).")]
public float maxSlideSpeed = 8f;
[Tooltip("How much steering control the player keeps while sliding " +
"(0 = none, 1 = full normal control).")]
[Range(0f, 1f)]
public float slideControl = 0.3f;
private CharacterController _controller;
private float _verticalVelocity;
// Ground contact normal collected from the latest Move (used for slope sliding).
private Vector3 _groundNormal = Vector3.up;
private bool _groundNormalUpdated;
private float _slideSpeed;
void Awake()
{
_controller = GetComponent();
if (cameraTransform == null && Camera.main != null)
cameraTransform = Camera.main.transform;
}
void Update()
{
// --- Read input -----------------------------------------------------
float h = 0f, v = 0f;
bool jumpPressed = false;
#if ENABLE_INPUT_SYSTEM
var keyboard = Keyboard.current;
if (keyboard != null)
{
if (keyboard.aKey.isPressed) h -= 1f;
if (keyboard.dKey.isPressed) h += 1f;
if (keyboard.sKey.isPressed) v -= 1f;
if (keyboard.wKey.isPressed) v += 1f;
jumpPressed = keyboard.spaceKey.wasPressedThisFrame;
}
#else
h = Input.GetAxisRaw("Horizontal");
v = Input.GetAxisRaw("Vertical");
jumpPressed = Input.GetButtonDown("Jump");
#endif
// --- Build the horizontal move direction ----------------------------
Vector3 inputDir = new Vector3(h, 0f, v);
if (inputDir.sqrMagnitude > 1f)
inputDir.Normalize();
Vector3 moveDir;
if (cameraRelative && cameraTransform != null)
{
// Project the camera axes onto the ground plane so movement stays horizontal.
Vector3 forward = cameraTransform.forward;
forward.y = 0f;
forward.Normalize();
Vector3 right = cameraTransform.right;
right.y = 0f;
right.Normalize();
moveDir = forward * inputDir.z + right * inputDir.x;
}
else
{
moveDir = inputDir;
}
// --- Evaluate the ground slope (for sliding) ------------------------
// The ground normal is gathered in OnControllerColliderHit during the
// previous Move. If it is steeper than the controller's Slope Limit, the
// surface is too steep to stand on (this also covers balancing on a sharp
// box edge/corner, whose contact normal is steep).
float slopeAngle = Vector3.Angle(_groundNormal, Vector3.up);
bool onSteepSlope = slideDownSteepSlopes
&& _controller.isGrounded
&& slopeAngle > _controller.slopeLimit + 0.01f;
// --- Gravity & jumping ---------------------------------------------
if (_controller.isGrounded)
{
// Reset accumulated fall speed and keep a small downward bias on the ground.
if (_verticalVelocity < 0f)
_verticalVelocity = groundedStickVelocity;
// No jumping off a slope that is too steep to stand on.
if (jumpPressed && !onSteepSlope)
_verticalVelocity = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
_verticalVelocity += gravity * Time.deltaTime;
// --- Slope sliding --------------------------------------------------
Vector3 slideVelocity = Vector3.zero;
if (onSteepSlope)
{
// Steepest-descent direction along the slope surface.
Vector3 slideDir = Vector3.ProjectOnPlane(Vector3.down, _groundNormal).normalized;
// Accelerate the slide up to the maximum slide speed.
_slideSpeed = Mathf.Min(_slideSpeed + slideAcceleration * Time.deltaTime, maxSlideSpeed);
slideVelocity = slideDir * _slideSpeed;
// While sliding the player keeps only reduced steering control.
moveDir *= slideControl;
}
else
{
_slideSpeed = 0f;
}
// --- Apply movement -------------------------------------------------
Vector3 velocity = moveDir * moveSpeed + slideVelocity + Vector3.up * _verticalVelocity;
// Reset the per-frame ground-normal collection, then Move (which fires
// OnControllerColliderHit), then fall back to "up" if nothing was hit.
_groundNormalUpdated = false;
_controller.Move(velocity * Time.deltaTime);
if (!_groundNormalUpdated)
_groundNormal = Vector3.up;
// --- Rotate toward the movement direction ---------------------------
if (rotateTowardMovement && moveDir.sqrMagnitude > 0.0001f)
{
Quaternion target = Quaternion.LookRotation(moveDir, Vector3.up);
transform.rotation = Quaternion.RotateTowards(
transform.rotation, target, rotationSpeed * Time.deltaTime);
}
}
///
/// Collects the ground contact normal during .
/// Walls and ceilings (normal pointing sideways or down) are ignored; among the
/// upward-facing contacts the flattest one is kept, which represents the surface
/// the character is actually standing on.
///
private void OnControllerColliderHit(ControllerColliderHit hit)
{
// Ignore near-vertical walls and ceilings.
if (hit.normal.y <= 0.05f)
return;
// Keep the flattest (most supportive) contact seen this frame.
if (!_groundNormalUpdated || hit.normal.y > _groundNormal.y)
{
_groundNormal = hit.normal;
_groundNormalUpdated = true;
}
}
}