Menu
CoddyTech

Pierdes

Parte de la sección Física y jugabilidad del Journey de Unity de Coddy. Lección 34 de 71.

Este paso completa Coin Rush: una pelota impulsada por fuerzas, monedas que actúan como desencadenadores, una puntuación controlada por un script y un reloj que termina la partida.

challenge icon

Desafío

Intermedio

Avísale al jugador cuando se acabe el tiempo primero.

  1. En Ball.cs, dentro de Update(), busca la línea que registra Time's up!.
  2. Justo después, registra You lose!.

Presiona «Jugar» y deja que se agote el tiempo: la consola muestra Time's up! Score: 0 y, después, You lose!. Luego, presiona «Comprobar».

Pruébalo tú mismo

using UnityEngine;

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

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

    void Update()
    {
        if (IsPlaying())
        {
            timeLeft -= Time.deltaTime;
            if (timeLeft <= 0f)
            {
                timeLeft = 0f;
                Debug.Log("Time's up! Score: " + score);
            }
        }
    }

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

    public void AddScore(int points)
    {
        if (!IsPlaying())
        {
            return;
        }
        score += points;
        Debug.Log("Score: " + score);
        if (score >= target)
        {
            Debug.Log("You win!");
        }
    }

    bool IsPlaying()
    {
        return timeLeft > 0f && score < target;
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Física y jugabilidad

Practica por tu cuenta: Playground de Unity