Menu
CoddyTech

The Rolling Ball

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

This chapter builds a small game, Coin Rush. You roll a ball around a walled arena with the arrows and collect coins before the clock runs out. Two scripts share the work, as they would in a Unity project: Ball moves the ball and will keep the score and the clock, and Coin sits on every coin. Coin.cs starts as an empty class, and the next lesson fills it in.

A ball rolls when you push it instead of placing it. Push its Rigidbody with AddForce and leave its rotation free: the force moves the ball, and friction from the floor grips the bottom of the ball and turns it. This bowling ball rolls down its lane while Space is held:

public float push = 6f;
private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    if (Input.GetKey(KeyCode.Space))
    {
        rb.AddForce(Vector3.forward * push);
    }
}

A ball that rolls without slipping spins at its speed divided by its radius, so a ball of radius 0.5 moving at 3 units per second turns at 6 radians per second (rb.angularVelocity). Change its transform.position instead, or freeze its rotation in the Rigidbody's Constraints, and it slides like a puck without turning. A plain one-colour sphere looks the same either way: to see the roll, watch Angular Velocity in the Rigidbody's Info section while the game plays.

challenge icon

Challenge

Medium

Start Coin Rush: roll the ball with the arrows.

  1. In Ball.cs's Start(), set rb = GetComponent<Rigidbody>();.
  2. In FixedUpdate(), read float x = Input.GetAxis("Horizontal"); and float z = Input.GetAxis("Vertical");, then call rb.AddForce(new Vector3(x, 0f, z) * force);.

Press Play, click the game and roll: the ball turns as it moves. Then Check.

Try it yourself

using UnityEngine;

public class Ball : MonoBehaviour
{
    public float force = 10f;
    private Rigidbody rb;

    void Start()
    {
    }

    void FixedUpdate()
    {
        // Push the ball with the arrows: Horizontal along x, Vertical along z.
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground