Prior to this lecture there was a challenge to “Implement Heath and damage system for attackers and projectiles”. This I did and it all worked out nicely, however there naturally are some differences to what Rick then does.
For example:
- I did not create a separate health script, as there was already an attacker scrip attached to the attacker lizard object, so I added the health stuff in that script (Mostly because I forgot it was on Ricks list).
- I put the OnTriggerEnter2D in the attacker scrip and not in the projectile script.
Basically I did it like we did in Laser Defender.
As I said it works, but I am unsure if it will cause problems later.
I want learn as much as possible and therefore I don’t really want to copy Rick 1 to 1.
using UnityEngine;
public class Attacker : MonoBehaviour
{
float currentSpeed = 1f;
[SerializeField] int health = 100;
void Update()
{
transform.Translate(Vector2.left * currentSpeed * Time.deltaTime);
}
public void SetMovementSpeed(float speed)
{
currentSpeed = speed;
}
private void OnTriggerEnter2D(Collider2D collidedWith)
{
DefenderShot defenderShot = collidedWith.gameObject.GetComponent<DefenderShot>();
if (!defenderShot)
{
return;
}
ProcessHit(defenderShot);
}
private void ProcessHit(DefenderShot defenderShot)
{
health -= defenderShot.GetDamage();
Debug.Log(health);
defenderShot.Hit();
if (health <= 0f)
{
EnemyDeath();
}
}
private void EnemyDeath()
{
Destroy(gameObject);
//To be iomplemeted
//DeathVFX
//DeathSFX
//AddToScore
}
}
using UnityEngine;
public class DefenderShot : MonoBehaviour
{
[SerializeField] float shotSpeed = 2f;
[SerializeField] int damage = 30;
void Update()
{
transform.Translate(Vector2.right * shotSpeed * Time.deltaTime);
}
public int GetDamage()
{
return damage;
}
public void Hit()
{
Destroy(gameObject);
}
}