Unity_Train/Assets/Player/PlayerControllerV2.cs

91 lines
No EOL
2.7 KiB
C#

using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControllerV2 : MonoBehaviour
{
private CharacterController m_CharacterController;
private Camera m_Camera;
private bool m_IsGrounded = false;
public float m_LookSensitivity = 25f;
public float m_PlayerSpeed = 500f;
public float m_MovementSmoothing = .05f;
private Vector2 m_MoveInput = Vector2.zero;
private Vector2 m_LookInput = Vector2.zero;
private Vector3 m_Velocity = Vector3.zero;
void Awake()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = GetComponentInChildren<Camera>();
Cursor.lockState = CursorLockMode.Locked;
}
void FixedUpdate()
{
m_IsGrounded = false;
RaycastHit hit; // TODO: Use to see if on train later and ground angle if that's relevant
if (Physics.Raycast(transform.position, Vector3.down, out hit, 1.1f))
{
m_IsGrounded = true;
}
Look();
Move();
}
private void Look()
{
m_CharacterController.transform.Rotate(Vector3.up * m_LookInput.x * m_LookSensitivity * Time.deltaTime);
float pitchRotation = m_Camera.transform.eulerAngles.x;
if (pitchRotation > 270) pitchRotation -= 360;
pitchRotation -= m_LookInput.y * m_LookSensitivity * Time.deltaTime;
//pitchRotation = Mathf.Clamp(pitchRotation, -90f, 90f);
m_Camera.transform.localRotation = Quaternion.Euler(pitchRotation, 0f, 0f);
}
private void Move()
{
// Horizontal movement
Vector3 direction = (transform.right * m_MoveInput.x +
transform.forward * m_MoveInput.y).normalized;
Vector3 horizontalMovement = m_Velocity;
horizontalMovement = Vector3.SmoothDamp(
m_CharacterController.velocity,
direction * m_PlayerSpeed * Time.deltaTime,
ref horizontalMovement,
m_MovementSmoothing);
m_Velocity.x = horizontalMovement.x;
m_Velocity.z = horizontalMovement.z;
// Vertical simulation
m_Velocity += 9.81f * -transform.up * Time.deltaTime; // Gravity
if (m_IsGrounded && m_Velocity.y < 0) // Reset negative velocity when landed
{
m_Velocity.y = -1 * Time.deltaTime;
}
m_CharacterController.Move(m_Velocity * Time.deltaTime);
}
void OnJump()
{
if (m_IsGrounded)
{
m_Velocity.y = 10;
m_IsGrounded = false;
}
}
void OnMove(InputValue value)
{
m_MoveInput = value.Get<Vector2>();
}
void OnLook(InputValue value)
{
m_LookInput = value.Get<Vector2>();
}
}