CSharp · Console
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float rotationSpeed;
public float jumpSpeed;
private CharacterController characterController;
private float ySpeed;
private float originalStepOffset;
// Start is called before the first frame update
void Start()
{
characterController = GetComponent<CharacterController>();
originalStepOffset = characterController.stepOffset;
}
// Update is called once per frame
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput);
float magnitude = Mathf.Clamp01(movementDirection.magnitude) * speed;
movementDirection.Normalize();
ySpeed += Physics.gravity.y * Time.deltaTime;
if (characterController.isGrounded)
{
characterController.stepOffset = originalStepOffset;
ySpeed = -0.5f;
if (Input.GetButtonDown("Jump"))
{
ySpeed = jumpSpeed;
}
}
else
{
characterController.stepOffset = 0;
}
Vector3 velocity = movementDirection * magnitude;
velocity = AdjustVelocityToSlope(velocity);
velocity.y += ySpeed;
characterController.Move(velocity * Time.deltaTime);
if (movementDirection != Vector3.zero)
{
Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
private Vector3 AdjustVelocityToSlope(Vector3 velocity)
{
var ray = new Ray(transform.position, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hitInfo, 0.2f))
{
var slopeRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
var adjustedVelocity = slopeRotation * velocity;
if (adjustedVelocity.y < 0)
{
return adjustedVelocity;
}
}
return velocity;
}
}