Hielo
Lección 21 de 25 del curso Juego de Unity: Defensa de torres de Coddy.
La torre Frost apenas hace daño, pero sus fragmentos ralentizan a un enemigo durante un tiempo. La ralentización es un estado de un enemigo y tiene un final: el enemigo conserva el factor y el tiempo en que termina la ralentización, y calcula su velocidad en cada fotograma a partir de la velocidad de su recurso. Mientras Time.time sea anterior al final, se aplica el factor; después, el enemigo recupera la velocidad máxima sin necesidad de revertir nada. Un coche de carreras sobre una plataforma de impulso:
public void Boost(float multiplier, float seconds)
{
boost = multiplier;
boostUntil = Time.time + seconds;
}float speed = data.topSpeed;
if (Time.time < boostUntil)
{
speed *= boost;
}La ralentización nunca debe escribirse en el recurso. data.speed *= 0.5f ralentizaría a todos los enemigos de ese tipo, incluidos los que aún no han aparecido, y nada restablecería la velocidad. Si un segundo fragmento alcanza a un enemigo ralentizado, vuelve a establecer el factor y el final, así que la ralentización dura mientras la torre Frost siga impactándolo y no se vuelve más intensa.
Desafío
IntermedioLos fragmentos de escarcha ralentizan a los enemigos durante un tiempo.
- En
TowerData, añadepublic float slowFactor = 1f;ypublic float slowDuration;(FrostData: 0.5 y 2). - En
Enemy,public void Slow(float factor, float duration)conserva el factor yslowUntil = Time.time + duration; muévete adata.speedmultiplicado por el factor mientrasTime.time < slowUntil. - En
Projectile, después del daño, cuandodata.slowDuration > 0y el objetivo tenga unEnemy, ralentízalo.
Pulsa «Jugar» con una torre Frost antes de tus Arrows: los Grunts escarchados caminan a la mitad de velocidad. Después, pulsa «Comprobar».
Pruébalo tú mismo
using System;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour, IDamageable
{
public static readonly List<Enemy> All = new List<Enemy>();
public static event Action<Enemy> ReachedBase;
public static event Action<Enemy> Killed;
public EnemyData data;
public Transform[] waypoints;
private int next = 1;
private int health;
void Awake()
{
health = data.maxHealth;
}
void OnEnable()
{
All.Add(this);
}
void OnDisable()
{
All.Remove(this);
}
void Update()
{
Vector3 target = waypoints[next].position;
transform.position = Vector3.MoveTowards(transform.position, target, data.speed * Time.deltaTime);
if (transform.position == target)
{
next++;
if (next == waypoints.Length)
{
ReachedBase?.Invoke(this);
Destroy(gameObject);
}
}
}
public void TakeDamage(int amount)
{
if (health <= 0)
{
return;
}
health -= amount;
if (health <= 0)
{
Killed?.Invoke(this);
Destroy(gameObject);
}
}
}
Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.
Todas las lecciones de Juego de Unity: Defensa de torres
Practica por tu cuenta: Playground de Unity