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
HardWrite the golf marble: aim, charge, shoot.
- Turn
aimwith the raw Horizontal axis ataimSpeed; putpointerattransform.position + Quaternion.Euler(0f, aim, 0f) * Vector3.forward. - At rest (speed under
stopSpeed), holding Space chargespowerbychargeRatetomaxPower; release kicks it along the aim (Impulse), resetspower, logs"Stroke " + strokes. - 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
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 WallPractice on your own: Unity playground