Files
Scampz/Assets/Scripts/Input/CharacterInputController.cs
Zenny b907cdcd9b Bug Fixes from v1.0
- Fix lighting on desert
- Move dialogue radius to correct spot
- Disable movement while talking to NPCs
- Move desert spawn point a little bit
2022-08-31 22:56:09 -07:00

105 lines
2.7 KiB
C#

using Scampz.GameJam.Assets.Scripts.Player;
using UnityEngine;
using UnityEngine.InputSystem;
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;
public PlayerControls playerControls;
private InputAction move;
private InputAction sprint;
public void EnableActions()
{
move.Enable();
}
public void DisableActions()
{
move.Disable();
}
private void Awake()
{
playerControls = new PlayerControls();
}
private void OnEnable()
{
move = playerControls.Player.Move;
sprint = playerControls.Player.Sprint;
move.Enable();
sprint.Enable();
}
private void OnDisable()
{
move.Disable();
sprint.Disable();
}
private void Start()
{
_controller = GetComponent<CharacterController>();
_playerState = GetComponent<PlayerState>();
}
void Update()
{
Move();
}
void Move()
{
var movementSpeed = Speed;
if (sprint.IsPressed())
movementSpeed *= 2;
var movement = move.ReadValue<Vector2>();
var movementDirection = new Vector3(-movement.x, 0, -movement.y);
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;
}
}
}