Beat the Clock
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 31 of 63.
Challenge
MediumAdd the clock. Keep everything from the earlier steps, and add to Ball:
public float timeLimit = 60f;(the Inspector sets 30) andpublic float timeLeft;. Being public,timeLeftshows in the Inspector, where you can watch it count down.- When the game starts,
timeLeftistimeLimit. Every frame while it is above 0, it goes down by the frame's time. - When it reaches 0, it stays at exactly 0, and the ball logs
Time's up! Score: 5once, with its score. - Once the time is up, the arrows no longer push the ball.
Press Play and see what you score in 30 seconds, 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
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall5Project: Coin Rush
The Rolling BallCoins to Collect