How to get rigidbody velocity?

How can I get a rigidbody velocity that I can make the value a float? Any help would be appreciated :slight_smile:

float speed = rigidbody.velocity.magnitude;
For example

float maxSpeed = 1.0f; // units/sec

void FixedUpdate() {
    Rigidbody rb = GetComponent<Rigidbody>();
    Vector3 vel = rb.velocity;
    if (vel.magnitude > maxSpeed) {
        rb.velocity = vel.normalized * maxSpeed;
    }
}

the velocity is a vector3. call magnitude on it and it returns its length as float

Rigidbody.velocity is a Vector3 because it’s not only an Amount of speed, it’s also a Direction.
If you wanted an object move forward for example, you would apply the following:

using UnityEngine;
using System.Collections;

public class MovingObject : MonoBehaviour
{
    public float m_speed = 20f;
    private Rigidbody m_rigidbody;

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

    void FixedUpdate()
    {
        // Makes this object move forward at X speed.
        m_rigidbody.velocity = m_speed * transform.forward;
    }
}

To apply force in a different direction you would just change “transform.forward” to something else like, choose one to your liking:

        m_rigidbody.velocity = m_speed * Vector3.up;  // Move Up
        m_rigidbody.velocity = m_speed * Vector3.left;  // Move left
        m_rigidbody.velocity = m_speed * Vector3.right;  // Move right
        m_rigidbody.velocity = m_speed * Vector3.back;  // Move back

I hope that helps, I’m always around for further questions, best of luck!! @Brylos