Files
agame_for_unity/Assets/_Game/Scripts/PlayerController.cs
T

65 lines
1.8 KiB
C#

using UnityEngine;
using UnityEngine.InputSystem;
namespace Agame
{
[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
[Header("Movement")]
public float moveSpeed = 5f;
public float sprintSpeed = 8f;
public float gravity = -20f;
public float jumpHeight = 1.5f;
private CharacterController controller;
private Vector3 velocity;
private bool isGrounded;
private void Awake()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
var kb = Keyboard.current;
if (kb == null)
{
return;
}
isGrounded = controller.isGrounded;
if (isGrounded && velocity.y < 0f)
{
velocity.y = -2f;
}
// WASD input
float moveX = 0f;
float moveZ = 0f;
if (kb.aKey.isPressed) moveX -= 1f;
if (kb.dKey.isPressed) moveX += 1f;
if (kb.sKey.isPressed) moveZ -= 1f;
if (kb.wKey.isPressed) moveZ += 1f;
// Move relative to the capsule's own facing (which MouseLook rotates)
Vector3 move = transform.right * moveX + transform.forward * moveZ;
move = Vector3.ClampMagnitude(move, 1f);
float speed = kb.leftShiftKey.isPressed ? sprintSpeed : moveSpeed;
controller.Move(move * speed * Time.deltaTime);
// Jump
if (kb.spaceKey.wasPressedThisFrame && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
// Gravity
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
}