Menu
CoddyTech

Sobreviva e Marque Pontos

Parte da seção Fundamentos de Scripting no Unity do Journey de Unity da Coddy. Lição 80 de 85.

Esta etapa finaliza Dodge the Blocks: um temporizador que gera blocos, uma lista que se move e limpa os blocos, um teste de colisão e uma pontuação que conta os segundos. (int) antes de um float descarta sua parte fracionária.

challenge icon

Desafio

Médio

Adicione uma pontuação e blocos que caem cada vez mais rápido.

  1. Adicione private float score; e [SerializeField] private float speedUp = 0.2f;.
  2. No início de Update(), adicione Time.deltaTime a score e speedUp * Time.deltaTime a fallSpeed.
  3. Ao ser atingido, registre "Game over! Score: " + (int)score. (int) remove a parte fracionária: 12.7 aparece como 12.

Pressione “Jogar” e sobreviva: um acerto registra sua pontuação. Depois, clique em “Verificar”.

Experimente você mesmo

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;
            Vector3 b = blocks[i].transform.position;
            if (Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f)
            {
                Debug.Log("Game over");
                enabled = false;
                return;
            }
            if (b.y < -1f)
            {
                Destroy(blocks[i]);
                blocks.RemoveAt(i);
            }
        }
    }
}
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Fundamentos de Scripting no Unity

Pratique por conta própria: Playground de Unity