To make sure the code @justinwolf wrote is bulletproof, you’ll want to add a bit of validation.
// Find the nearest Entity with the type "box" to
// this Entity and attempt to cast it to a Box object.
var near:Box = world.nearestToEntity("box", this) as Box;
// Make sure the found Entity is actually a Box by checking against null.
if (near != null && near.isTouched)
{
// The found Entity is a Box and isTouched is true.
// Perform any desired touching logic.
...
}
Even with that additional validation, @B6ka is asking the right question. nearestToEntity()
finds the closest Entity a specified Entity of a desired type; however, the Entity’s type
property doesn’t necessarily imply a specific class.
Consider a game with entities Spike
and AeroChaser
, both of which have a type
of harmful. Whenever the player touches either of them, the player will lose health; however, if the player touches an AeroChaser
, the AeroChaser
will also take damage.
The following code will result in a crash if the player touches a Spike
.
var near:AeroChaser = world.nearestToEntity("harmful", this) as AeroChaser;
if (near != null && near.isTouched)
{
takeDamage(near.contactDamage);
near.takeDamage(contactDamage);
}
This leads to the following problem: How can I get the closest entity of a specific type? Should this be an additional argument in this family of functions?
public function nearestToEntity(type:String, e:Entity, useHitboxes:Boolean = false, entityClass:Class = null):Entity