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
MediumStart Coin Rush: roll the ball with the arrows.
- In
Ball.cs'sStart(), setrb = GetComponent<Rigidbody>();. - In
FixedUpdate(), readfloat x = Input.GetAxis("Horizontal");andfloat z = Input.GetAxis("Vertical");, then callrb.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
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 Wall5Project: Coin Rush
The Rolling BallCoins to CollectPractice on your own: Unity playground