Menu
CoddyTech

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 icon

Challenge

Easy

Push the puck around the frictionless rink with forces.

  1. In FixedUpdate(), read float h = Input.GetAxis("Horizontal"); and float v = Input.GetAxis("Vertical");.
  2. Call rb.AddForce(new Vector3(h, 0, v) * push);, with no Time.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

Practice on your own: Unity playground