rleob
rleob

Reputation: 25

How could I clamp the acceleration with movement like this?

I'm not sure how to stop it from accelerating forever.

    [SerializeField] float moveSpeed;
    [SerializeField] float turnSpeed;
    [SerializeField] float maxForwardVelocity;

    private Rigidbody rigidbody;

    private void Start()
    {
        rigidbody = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        if(Input.GetAxis("Vertical") != 0)
        {
            float rotateInput = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
            transform.eulerAngles += new Vector3(0f, rotateInput, 0f);
        }

        float forwardInput = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
        rigidbody.AddRelativeForce(new Vector3(forwardInput, 0f, 0f));
    }

Upvotes: 1

Views: 103

Answers (1)

Ruzihm
Ruzihm

Reputation: 20269

First, you should do physics calculations in FixedUpdate.

Second, using some vector math you can calculate the acceleration to apply. Explanation in comments:

float rotateInput;
float forwardInput;

private void Update()
{
    rotateInput = 0f;
    if(Input.GetAxis("Vertical") != 0)
    {
        rotateInput = Input.GetAxis("Horizontal") * turnSpeed;        
    }

    forwardInput = Input.GetAxis("Vertical") * moveSpeed;
}

void FixedUpdate()
{
    transform.eulerAngles += new Vector3(0f, rotateInput * Time.deltaTime, 0f);

    // How much the current frame wants to change velocity in the forward direction
    float uncappedForwardDS = forwardInput 
            * Time.deltaTime * Time.deltaTime / rigidbody.mass;

    // How fast are we going in the forward direction
    float curForwardSpeed = Vector3.Dot(transform.forward, rigidbody.velocity);

    // prevent braking effect when going forward (don't "accelerate" less than 0)
    float availableForwardDS = Mathf.Max(0f, maxForwardVelocity - curForwardSpeed);

    // Cap the relative delta speed
    float cappedRelDS = Mathf.Min(uncappedForwardDS, availableForwardDS);

    // Mass and deltaTime of frame already accounted for, so apply with VelocityChange
    rigidbody.AddRelativeForce(new Vector3(cappedRelDS, 0f, 0f), 
            ForceMode.VelocityChange);
}

Upvotes: 1

Related Questions