Win or Lose
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 32 of 63.
Challenge
MediumLast step: a way to win. Keep everything from the earlier steps, and add to Ball:
public int target = 10;(the Inspector sets 8).- The game is on while
timeLeftis above 0 andscoreis belowtarget. Write that as a method,bool IsPlaying(), and use it: the clock counts down, the arrows push and coins add to the score only while the game is on. - When a coin brings
scoreup totargetor more, logYou win!after the score line. - When the time runs out first, log
You lose!after theTime's up!line.
Press Play and reach 8 points before the clock runs out, then Check.
Try it yourself
using UnityEngine;
public class Ball : MonoBehaviour
{
public float force = 10f;
public int score;
public float timeLimit = 60f;
public float timeLeft;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
timeLeft = timeLimit;
}
void Update()
{
if (timeLeft > 0f)
{
timeLeft -= Time.deltaTime;
if (timeLeft <= 0f)
{
timeLeft = 0f;
Debug.Log("Time's up! Score: " + score);
}
}
}
void FixedUpdate()
{
if (timeLeft > 0f)
{
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