O
O
Orehktatura2020-10-27 08:03:24
C++ / C#
Orehktatura, 2020-10-27 08:03:24

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

1 answer(s)
F
freeExec, 2020-10-27
@freeExec

Create a new universe, where the speed of light would be less :)
And so at least limit the use of force per unit time, multiplying by Time.deltaFixedTime. Unless of course you do not neglect the resistance, and so you need to apply force only once.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question