ccl4/blueberryPeak/Assets/Scripts/Player/PlayerMovement.cs
2025-06-19 19:44:07 +02:00

96 lines
2.8 KiB
C#

using UnityEngine;
using UnityEngine.InputSystem;
using Event = AK.Wwise.Event;
[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
[Header("Movement Settings")] [SerializeField]
private float movementSpeed = 5f;
[SerializeField] private float rotationSpeed = 200f;
[SerializeField] private InputActionReference movement;
[SerializeField] private Transform cameraTransform;
[SerializeField] private Vector3 cameraOffset = new(0, 10, -10);
[SerializeField] private Animator _animator;
[Header("Footstep Sound Settings")] [SerializeField]
private Event footstepEvent;
[SerializeField] private float footstepInterval = 0.5f; // seconds between footsteps
public bool moveAllowed = true;
private CharacterController controller;
private float footstepTimer;
private Vector3 inputDirection = Vector3.zero;
private void Start()
{
controller = GetComponent<CharacterController>();
movement.action.Enable();
movement.action.performed += OnMovement;
movement.action.canceled += OnMovementStop;
}
private void Update()
{
Cursor.lockState = CursorLockMode.Locked;
var cameraForward = cameraTransform.forward;
var cameraRight = cameraTransform.right;
cameraForward.y = 0;
cameraRight.y = 0;
cameraForward.Normalize();
cameraRight.Normalize();
var move = (cameraForward * inputDirection.z + cameraRight * inputDirection.x).normalized * movementSpeed;
controller.SimpleMove(move);
_animator.SetFloat("Speed", move.magnitude);
if (move.magnitude > 0.01f)
{
var toRotation = Quaternion.LookRotation(move, Vector3.up);
transform.rotation =
Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
// Footstep logic
footstepTimer -= Time.deltaTime;
if (footstepTimer <= 0f && footstepEvent != null)
{
footstepEvent.Post(gameObject);
footstepTimer = footstepInterval;
}
}
else
{
footstepTimer = 0f; // Reset when not moving
}
}
private void LateUpdate()
{
if (cameraTransform != null)
{
cameraTransform.position = transform.position + cameraOffset;
cameraTransform.LookAt(transform.position);
}
}
private void OnMovement(InputAction.CallbackContext context)
{
if (moveAllowed)
{
var inputVector = context.ReadValue<Vector2>();
inputDirection = new Vector3(inputVector.x, 0, inputVector.y);
}
}
private void OnMovementStop(InputAction.CallbackContext context)
{
inputDirection = Vector3.zero;
}
}