[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class MoveController : MonoBehaviour
{
public float Speed = 0.3f; //Переменная силы скорости
public float JumpForce = 1f; //переменная силы прыжка
public LayerMask GroundLayer = 1; // слой по дефолту
private CapsuleCollider _collider; //Обращение к колайдеру
private Rigidbody _rb; //Обращение к риджетбади
private bool _isGrounded
{
get
{
var bottomCenterPoint = new Vector3(_collider.bounds.center.x, _collider.bounds.min.y, _collider.bounds.center.z);
return Physics.CheckCapsule(_collider.bounds.center, bottomCenterPoint, _collider.bounds.size.x / 2 * 0.9f, GroundLayer);
}
}
private Vector3 _movementVector
{
get
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
return new Vector3(horizontal, 0.0f, vertical);
}
}
void Start()
{
_rb = GetComponent<Rigidbody>();
_collider = GetComponent<CapsuleCollider>();
_rb.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationY;
if (GroundLayer == gameObject.layer)
{
Debug.LogError("Player Sorting Layer must be different from Ground SourlingLayer!");
}
}
void FixedUpdate()
{
JumpLogic();
MovementLogic();
}
private void MovementLogic()
{
_rb.AddForce(_movementVector * Speed, ForceMode.Impulse) ;
}
private void JumpLogic()
{
if (_isGrounded && Input.GetAxis("Jump") > 0)
{
_rb.AddForce(Vector3.up * JumpForce, ForceMode.Impulse);
}
}