Menu
CoddyTech

Beat the Clock

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

challenge icon

Challenge

Medium

Add a clock to Coin Rush.

  1. In Ball.cs, add public float timeLimit = 60f; and public float timeLeft;; set timeLeft = timeLimit; in Start().
  2. In a new Update(), while timeLeft > 0f, take Time.deltaTime off it; at 0, set it to 0f and log "Time's up! Score: " + score.
  3. In FixedUpdate(), push only while timeLeft > 0f.

Press Play and watch the clock. Then Check.

Try it yourself

using UnityEngine;

public class Ball : MonoBehaviour
{
    public float force = 10f;
    public int score;
    private Rigidbody rb;

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

    void FixedUpdate()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        rb.AddForce(new Vector3(x, 0f, z) * force);
    }

    public void AddScore(int points)
    {
        score += points;
        Debug.Log("Score: " + score);
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground