Answer the question
In order to leave comments, you need to log in
How can I limit the maximum speed so that the object does not accelerate to infinity?
[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);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question