Need help with C# and velocity calculation

Hey all,

I’m pretty new to C# programming so if there is an obvious answer (most likely) don’t judge me too harshly.

I’m trying to limit the velocity on an object and have no clue how to do that. I can make the rigid-body move with rigidbody.AddRelitiveForce but I’m having trouble figuring out how to limit that acceleration/speed. Any help is appreciated.

Here’s my code:

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

    public GameObject Player;
    public float RotationSpeed = 2.75f;
    public float EngineSpeed = 2;
    
    public bool engineOnOff = false;
    
    public float maxSpeed = 1.5f;
    private float currentSpeed = 0.0f;
    

    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetButton("Engine")==true) {
            engineOnOff = true;
        }else{
            engineOnOff = false;
            }
        if (Input.GetButton("Left")==true) {
            transform.Rotate(Vector3.down * (Time.deltaTime + RotationSpeed));
        }
        if (Input.GetButton("Right")) {
            transform.Rotate(Vector3.up * (Time.deltaTime + RotationSpeed));
        }
    }
    
    void FixedUpdate() {
        if (engineOnOff==true) {
        //transform.Translate(Vector3.forward * (Time.deltaTime * maxSpeed));
            //currentSpeed = Player.vector3.forward;
            print(rigidbody.velocity);
            if (currentSpeed < maxSpeed) {
            rigidbody.AddRelativeForce(Vector3.forward * Time.deltaTime * maxSpeed);
            }
        }
    }
}

Edit:
I’m trying to make an Asteroids replica as practice and to learn the engine/language better.
I also know a little java but I’m trying to go cold-turkey and learn C#… I’m pulling my hair out! :smile:

You could try setting velocity directly if it’s above the threshold.

currentspeed = rigidbody.velocity.magnitude;
if (currentspeed > maxSpeed) { rigidbody.velocity = rigidbody.velocity.normalized*maxSpeed;}

Also, i think you wanted Time.fixedDeltaTime instead of deltaTime in FixedUpdate

Thank you very much ValooFX! It works great! I’m going to study WHY it works as I don’t quite understand it yet lol

Why use Time.fixedDeltaTime in the FixedUpdate?

Regards,
Sedare