Menu
CoddyTech

The Rolling Ball

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 27 of 63.

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 with the ball. The Inspector gives Ball a force of 10.

  • In Start(), store the ball's Rigidbody in rb.
  • In FixedUpdate(), push the ball with the arrows: Input.GetAxis("Horizontal") along x and Input.GetAxis("Vertical") along z, both times force.
  • Leave its rotation free, so it rolls.

Leave Coin.cs as it is for now. Press Play, click the game and roll around the arena, 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.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay