Menu
CoddyTech

Estrela Após Estrela

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

challenge icon

Desafio

Médio

Envie uma nova estrela após cada captura e cada erro.

  1. Escreva void ResetStar() que define star.position = new Vector3(Random.Range(-4f, 4f), 6f, 0f); e chame-a na captura em vez da linha antiga.
  2. Após o if da captura, adicione else if (star.position.y < 0f) que chama ResetStar();. Um else if é executado somente quando o if anterior era falso.

Pressione “Jogar”: cada nova estrela cai em um novo x. Depois, pressione “Verificar”.

Experimente você mesmo

using UnityEngine;

public class Catcher : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private Transform star;
    [SerializeField] private float fallSpeed = 3f;
    private int score;

    void Update()
    {
        float x = transform.position.x;
        if (Input.GetKey(KeyCode.RightArrow))
        {
            x += speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            x -= speed * Time.deltaTime;
        }
        x = Mathf.Clamp(x, -4f, 4f);
        transform.position = new Vector3(x, transform.position.y, transform.position.z);

        star.position += Vector3.down * fallSpeed * Time.deltaTime;

        if (Vector3.Distance(transform.position, star.position) < 1f)
        {
            score++;
            Debug.Log("Caught! Score: " + score);
            star.position = new Vector3(star.position.x, 6f, star.position.z);
        }
    }
}

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

Pratique por conta própria: Playground de Unity