Search code examples
actionscript-3flashentityflashdevelop

Flashpunk. Ways of adding entity to the World


Okay when I was going through different resources on Flashpunk I found three ways of adding entities to the world:

add(new Entity(10, 10));
//***************
var _entity:Entity;
//In constructor:
_entity = new Entity(10,10);
add(_entity);
//***************
FP.world.add(new Entity(10,10));

So my question is which one should I use and when.

Thank you.


Solution

  • add(new Entity(10, 10));
    

    This will only work in whichever context add() is defined. I haven't used this specific library, but assuming that will be in a class called something similar to World and anything that inherits from it.

    var entity:Entity = new Entity(10, 10);
    add(entity);
    

    This just breaks up the first example into two lines. It will also let you refer to that specific Entity before and after adding it to the world, whereas in the other example you have no way to reference the Entity you added.

    FP.world.add(new Entity(10,10));
    

    Here I'm assuming there's a class FP with the static property world representing a current relevant instance of the World. It does the same thing as the first example except that you can do this in any context. I would avoid using this; you'll find yourself using it as an excuse to add things to the world from unexpected locations in your code, leading to reduced code readability, frustration and a much harder debugging experience.

    My preference is example 2. It's more readable, it suggests that you're using add within an appropriate context, and it lets you make changes to the Entity that you create:

    var entity:Entity = new Entity();
    entity.property = newValue;
    
    add(entity);