Menu
CoddyTech

Marble Golf

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

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

Write the golf marble: aim, charge, shoot.

  1. Turn aim with the raw Horizontal axis at aimSpeed; put pointer at transform.position + Quaternion.Euler(0f, aim, 0f) * Vector3.forward.
  2. At rest (speed under stopSpeed), holding Space charges power by chargeRate to maxPower; release kicks it along the aim (Impulse), resets power, logs "Stroke " + strokes.
  3. In FixedUpdate(), at rest, zero both velocities.

Press Play and putt. 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
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground