67 lines
1.9 KiB
C#
67 lines
1.9 KiB
C#
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 void Start()
|
|
{
|
|
_controller = GetComponent<CharacterController>();
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
Move();
|
|
}
|
|
|
|
void Move()
|
|
{
|
|
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) * Speed;
|
|
movementDirection.Normalize();
|
|
_ySpeed += Physics.gravity.y * Time.deltaTime;
|
|
|
|
if (_controller.isGrounded)
|
|
_ySpeed -= 0.5f;
|
|
|
|
var velocity = movementDirection * magnitude;
|
|
velocity = AdjustVelocityToSlope(velocity);
|
|
velocity.y += _ySpeed;
|
|
|
|
_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;
|
|
}
|
|
}
|
|
}
|