Adi
Adi

Reputation: 71

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;
        }
    }
}

Upvotes: 3

Views: 12638

Answers (2)

Utopia
Utopia

Reputation: 663

only this:

void Update() {
rb2D.velocity = Vector3.ClampMagnitude(rb2D.velocity, maxSpeed);
}

Upvotes: 5

Adi
Adi

Reputation: 71

I need to sleep more. Just change veloc.magnitude to rb2D.velocity.magnitude in the FixedUpdate method if you had a similar problem. The object does 'stutter' upon reaching max velocity but I am yet to find a solution to that.

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

    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(rb2D.velocity.magnitude > maxSpeed)
        {
            rb2D.velocity = rb2D.velocity.normalized * maxSpeed;
        }
    }
}

Upvotes: 3

Related Questions