Push with AddForce
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 2 of 71.
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
EasyPush the puck around the frictionless rink with forces.
- In
FixedUpdate(), readfloat h = Input.GetAxis("Horizontal");andfloat v = Input.GetAxis("Vertical");. - Call
rb.AddForce(new Vector3(h, 0, v) * push);, with noTime.deltaTime.
Press Play, push and let go: the puck keeps gliding. 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
}
}
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