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
EasyWalk the robot at exactly speed m/s, and let it fall off the edge.
- In
FixedUpdate(), readfloat h = Input.GetAxisRaw("Horizontal");andfloat vfrom"Vertical". - 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
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground