Push with AddForce
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 2 of 63.
Once an object has a Rigidbody, physics moves it, so you stop changing its position and push it instead. rb.AddForce(force) pushes the body with a force, a Vector3 in newtons. A force does not set a speed: it speeds the body up for as long as you keep adding it, by the force divided by the mass every second. Stop pushing and the body keeps the speed it has.
This hovercraft (2 kg) has a thruster: while the up arrow is held, a force of thrust pushes it forward, along +z. With a thrust of 12, it gains 12 / 2 = 6 m/s every second:
public float thrust = 12f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.UpArrow))
{
rb.AddForce(Vector3.forward * thrust);
}
}Forces go in FixedUpdate(), which Unity calls before each physics step, 50 times a second (lesson 4 explains why). There is no Time.deltaTime in the line: AddForce already spreads the force over the step, and multiplying by Time.deltaTime would make the push 50 times weaker. On the ground, friction pushes back, so a small force may not move a heavy box at all.
Challenge
EasyThe puck on the ice rink has a Rigidbody, and the ice has no friction. Push it with the arrows: the Horizontal axis pushes it along x and the Vertical axis along z, with a force of push (4 in the Inspector).
Push it with forces only, so it keeps gliding when you let go. Press Play, steer the puck around the rink, then Check.
Try it yourself
using UnityEngine;
public class PuckPusher : MonoBehaviour
{
public float push = 4f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
// Push the puck: Horizontal along x, Vertical along z
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall