Menu
CoddyTech

¡Choque!

Parte de la sección Fundamentos de scripting en Unity del Journey de Unity de Coddy. Lección 79 de 85.

challenge icon

Desafío

Intermedio

Termina el juego cuando un bloque toque al corredor.

  1. En el bucle de bloques, después de que un bloque se mueva, lee su posición como Vector3 b.
  2. Cuando Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f, registra Game over, establece enabled = false; y ejecuta return;.

Pulsa «Jugar» y deja que un bloque caiga sobre ti: la consola muestra Game over y todo se detiene. Después, pulsa «Comprobar».

Pruébalo tú mismo

using System.Collections.Generic;
using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;
    [SerializeField] private GameObject blockPrefab;
    [SerializeField] private float spawnEvery = 1f;
    [SerializeField] private float fallSpeed = 5f;

    private List<GameObject> blocks = new List<GameObject>();
    private float timer;

    void Update()
    {
        Vector3 p = transform.position;
        p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
        transform.position = p;

        timer += Time.deltaTime;
        if (timer >= spawnEvery)
        {
            timer -= spawnEvery;
            Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
            blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
        }

        for (int i = blocks.Count - 1; i >= 0; i--)
        {
            blocks[i].transform.position += Vector3.down * fallSpeed * Time.deltaTime;
            if (blocks[i].transform.position.y < -1f)
            {
                Destroy(blocks[i]);
                blocks.RemoveAt(i);
            }
        }
    }
}

Todas las lecciones de Fundamentos de scripting en Unity

Practica por tu cuenta: Playground de Unity