Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set maximum velocity of a rigidbody in Unity?

Nothing seems to work, played around for a few hours, copied and pasted 'solutions' from google but nope.
Changing the maxSpeed variable doesn't do anything. Object still flies across the screen like Barry Allen.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour 
{

    [Range (0, 5)]public int speed;
    public Rigidbody2D rb2D;
    public Vector3 veloc;
    public float maxSpeed;

    void Start () 
    {
        rb2D = GetComponent<Rigidbody2D> ();
        speed = 4;
        maxSpeed = 0.01f;
        veloc = GetComponent <Rigidbody2D>().velocity;
    }

    void Update () 
    {
        if(Input.GetKey(KeyCode.W))
        {
            rb2D.AddForce (Vector3.up * speed);
        }
        if(Input.GetKey(KeyCode.S))
        {
            rb2D.AddForce (-Vector3.up * speed);
        }
        if(Input.GetKey(KeyCode.D))
        {
            rb2D.AddForce (Vector3.right * speed);
        }
        if(Input.GetKey(KeyCode.A))
        {
            rb2D.AddForce (-Vector3.right * speed);
        }
    }
    void FixedUpdate ()
    {
        if(veloc.magnitude > maxSpeed)
        {
            rb2D.velocity = rb2D.velocity.normalized * maxSpeed;
        }
    }
}
like image 502
Adi Avatar asked Dec 13 '25 09:12

Adi


1 Answers

only this:

void Update() {
rb2D.velocity = Vector3.ClampMagnitude(rb2D.velocity, maxSpeed);
}
like image 160
Utopia Avatar answered Dec 15 '25 09:12

Utopia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!