Menu
CoddyTech

Velocity

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 5 of 63.

rb.linearVelocity is how the body is moving right now: a Vector3 in metres per second along x, y and z. Reading it tells you where the body is heading, and rb.linearVelocity.magnitude is its speed. Setting it changes the motion at once, with no ramp-up and no mass involved: a 1 kg box and a 50 kg safe set to 2 m/s both move at exactly 2 m/s from the next physics step. Gravity, friction and hits keep acting on it afterwards.

This go-kart drives forward at exactly cruise m/s. It copies the velocity, changes only z and assigns it back, so the y that gravity gave it stays and the kart still drops off the end of a ramp:

void FixedUpdate()
{
    Vector3 vel = rb.linearVelocity;
    vel.z = cruise;            // forward at exactly cruise m/s
    rb.linearVelocity = vel;   // y keeps what gravity made it
}

Setting y to 0 as well would throw away gravity's speed on every step, and the kart would drift down off the ramp instead of falling. Before Unity 6 this property was called velocity. Old tutorials still write rb.velocity: in Unity 6 it compiles, with a warning that velocity is obsolete and has been renamed to linearVelocity. drag became linearDamping the same way. Write the new names.

challenge icon

Challenge

Easy

The robot walks on a raised platform. Make the arrows walk it at exactly speed m/s (3 in the Inspector): left and right along x, up and down along z, using the raw axes so there is no easing.

  • With no arrow held, it stands still at once.
  • Gravity still works: walked off the edge, the robot falls to the ground below.

Press Play and walk it off the edge, then Check.

Try it yourself

using UnityEngine;

public class RobotWalk : MonoBehaviour
{
    public float speed = 3f;
    private Rigidbody rb;

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

    void FixedUpdate()
    {
        // Walk at exactly speed with the arrows, keeping gravity's y
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay