Or, you can go even further and have the colliding type deal with the damage. Let’s also add an interface for extra OOP!
IDealsDamage
public interface IDealsDamage
{
function dealDamage(target:Hero):void;
}
Imp
public class Imp extends Entity implements IDealsDamage
{
public function Imp()
{
// Imps are enemies.
type = "enemy";
}
public function dealDamage(target:Hero):void
{
// Imps just deal damage.
target.health -= 2;
}
}
Snake
public class Snake extends Entity implements IDealsDamage
{
public function Snake()
{
// Snakes are enemies.
type = "enemy";
}
public function dealDamage(target:Hero):void
{
// Snakes deal less damage, but also poison.
target.health -= 1;
target.poisoned = true;
}
}
Cat
public class Cat extends Entity
{
public function Cat()
{
// Cats are enemies.
type = "enemy";
}
// Cats can't hurt people, bro.
}
GameWorld
public class GameWorld extends World
{
private var _hero:Hero;
override public function update():void
{
var collidingEntity:Entity = _hero.collide("enemy", _hero.x, _hero.y);
if (collidingEntity != null)
{
// The hero has collided with an enemy.
if (collidingEntity is IDealsDamage)
{
// The hero has collided with a damage dealer.
IDealsDamage(collidingEntity).dealDamage(_hero);
}
}
}
}
Now, whenever the hero collides with an Imp
or a Snake
, it will call dealDamage()
, but if the hero collides with a Cat
, no damage will be dealt. And that’s dope.