Files
PIM_Laba2/Assets/_Scripts/Mover.cs
T
2026-05-25 20:45:05 +03:00

51 lines
1.5 KiB
C#

using UnityEngine;
[RequireComponent(typeof(Rigidbody), typeof(BoxCollider), typeof(PlayerInput))]
public class Mover : MonoBehaviour
{
[SerializeField] private float moveSpeed = 6f;
[SerializeField] private float jumpForce = 7f;
[SerializeField] private float groundCheckExtraDistance = 0.1f;
private Rigidbody rb;
private BoxCollider boxCollider;
private PlayerInput playerInput;
private void Awake()
{
rb = GetComponent<Rigidbody>();
boxCollider = GetComponent<BoxCollider>();
playerInput = GetComponent<PlayerInput>();
rb.freezeRotation = true;
}
private void FixedUpdate()
{
Vector3 moveDirection = playerInput.MoveInput;
Vector3 targetVelocity = new Vector3(
moveDirection.x * moveSpeed,
rb.velocity.y,
moveDirection.z * moveSpeed);
rb.velocity = targetVelocity;
if (moveDirection.sqrMagnitude > 0.001f)
{
transform.forward = moveDirection;
}
if (playerInput.ConsumeJump() && IsGrounded())
{
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
private bool IsGrounded()
{
Bounds bounds = boxCollider.bounds;
float rayDistance = bounds.extents.y + groundCheckExtraDistance;
return Physics.Raycast(bounds.center, Vector3.down, rayDistance, Physics.DefaultRaycastLayers, QueryTriggerInteraction.Ignore);
}
}