74 lines
2.2 KiB
C#
74 lines
2.2 KiB
C#
using Scampz.GameJam.Assets.Scripts.Player;
|
|
using UnityEngine;
|
|
|
|
namespace Scampz.GameJam.Assets.Scripts
|
|
{
|
|
public class CharacterInputController : MonoBehaviour
|
|
{
|
|
private CharacterController _controller;
|
|
public float Speed = 10f;
|
|
public float RotateSpeed = 720.0f;
|
|
private float _ySpeed = 0f;
|
|
private PlayerState _playerState;
|
|
|
|
private void Start()
|
|
{
|
|
_controller = GetComponent<CharacterController>();
|
|
_playerState = GetComponent<PlayerState>();
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
Move();
|
|
}
|
|
|
|
void Move()
|
|
{
|
|
var movementSpeed = Speed;
|
|
if (Input.GetButton(InputOptions.Sprint))
|
|
movementSpeed *= 2;
|
|
var horizontalMovement = Input.GetAxisRaw(InputOptions.Horizontal);
|
|
var verticalMovement = Input.GetAxisRaw(InputOptions.Vertical);
|
|
|
|
var movementDirection = new Vector3(-horizontalMovement, 0, -verticalMovement);
|
|
var magnitude = Mathf.Clamp01(movementDirection.magnitude) * movementSpeed;
|
|
movementDirection.Normalize();
|
|
_ySpeed += Physics.gravity.y * Time.deltaTime;
|
|
|
|
if (_controller.isGrounded)
|
|
_ySpeed -= 0.5f;
|
|
|
|
var velocity = movementDirection * magnitude;
|
|
velocity = AdjustVelocityToSlope(velocity);
|
|
velocity.y += _ySpeed;
|
|
|
|
if (_playerState.CanMove)
|
|
_controller.Move(velocity * Time.deltaTime);
|
|
|
|
if (movementDirection != Vector3.zero)
|
|
{
|
|
var ray = new Ray(transform.position, Vector3.down);
|
|
Physics.Raycast(ray, out var hitInfo, 5f);
|
|
var toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
|
|
toRotation.x = Quaternion.LookRotation(Vector3.Cross(transform.right, hitInfo.normal)).x;
|
|
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, RotateSpeed * Time.deltaTime);
|
|
}
|
|
}
|
|
|
|
private Vector3 AdjustVelocityToSlope(Vector3 velocity)
|
|
{
|
|
var ray = new Ray(transform.position, Vector3.down);
|
|
|
|
if (Physics.Raycast(ray, out var hitInfo, 5f))
|
|
{
|
|
var slopeRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
|
|
var adjustedVelocity = slopeRotation * velocity;
|
|
if (adjustedVelocity.y < 0)
|
|
return adjustedVelocity;
|
|
}
|
|
|
|
return velocity;
|
|
}
|
|
}
|
|
}
|