Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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));
    }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!