Menu
CoddyTech

Marble Golf

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

Golf with a marble on a little green. The marble starts on the tee: you aim it with the arrows, hold Space to build up power and let go to shoot. It rolls, bounces off the cushions and the block in the middle, and slows down, and once it is slow enough it stops dead. Only then can you shoot again. A marble that rolls onto the cup slowly drops in; one that arrives too fast rolls straight over it. The fewer strokes, the better.

Write two scripts: Golf on the marble and Hole on the cup.

challenge icon

Challenge

Hard

The Inspector gives Golf pointer (the small yellow ball), aimSpeed (90), chargeRate (4), maxPower (6) and stopSpeed (0.3). The marble's mass is 0.5.

  • The aim is an angle around y, 0 at the start (straight ahead, +z). The right arrow turns it right and the left arrow left, at aimSpeed degrees per second. Every frame, put the pointer 1 unit from the marble in the aim's direction.
  • The marble is at rest while its speed is below stopSpeed. In every physics step, a marble at rest is stopped dead: velocity and angular velocity zero.
  • Only while the marble is at rest: holding Space builds up power at chargeRate per second, never above maxPower, and letting go of Space kicks the marble with an Impulse of that power along the aim. The power then goes back to 0, and a public int strokes goes up by 1 and is logged, as Stroke 1.

The Inspector gives Hole sinkSpeed (3).

  • When the marble (the object with the Golf script) enters the cup slower than sinkSpeed, log its strokes, as In the cup in 2 strokes!, and deactivate the marble. A faster marble rolls over.

Press Play and sink the marble in as few strokes as you can, then Check.

Try it yourself

using UnityEngine;

public class Golf : MonoBehaviour
{
    public int strokes = 0;
    [SerializeField] private Transform pointer;
    [SerializeField] private float aimSpeed = 90f;
    [SerializeField] private float chargeRate = 4f;
    [SerializeField] private float maxPower = 6f;
    [SerializeField] private float stopSpeed = 0.3f;
    private Rigidbody rb;

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

    // aim with the arrows, charge with Space, shoot on release, stop when slow
}
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