Menu
CoddyTech

Velocity

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

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

Walk the robot at exactly speed m/s, and let it fall off the edge.

  1. In FixedUpdate(), read float h = Input.GetAxisRaw("Horizontal"); and float v from "Vertical".
  2. Set rb.linearVelocity = new Vector3(h * speed, rb.linearVelocity.y, v * speed);, keeping gravity's y.

Press Play and walk off the edge: the robot stops when you let go, and falls. 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
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground