There seems to be some confusion about when the constructor function is ran. The constructor function, as the name indicates, is ran when the object is constructed. This means it's ran at
which, kind of is ran in
world.create (it's a bit more complicated than that, pooling, but whatever, it does create new bullets at a point).
So, breaking down what you're doing:
var bullet:Bullet = Bullet(world.create(Bullet, true)); //new Bullet() goes here!
You can see that you're running the constructer first (in which you're not setting any variables to anything, thus they'll trace out
0) and only afterwards running the
init() function (in which you do set variables). If you try tracing them out after all variables are set (i.e. bottom of init function), hopefully everything's okay!
So, you may be wondering, How come I can't just use
new Bullet() and put my logic in the constructor?
Well, that's the thing with
world.create(). As I mentioned in a long parenthesis a couple of lines back,
create() uses pooling, which basically:
- Checks if there are any X (in your case bullets) in the pool.
- If so, return that X, instead of creating a new one. Skip to 4.
- If not, create a new X, add it to the pool for future use, and returned it.
- The end.
You can see how this is a lot better than always creating new entities for stuff that could get reused a lot. Like, say, bullets. But if you're fetching an old X from the pool, you can't really re-run its constructor, since you're not constructing it. That's where a function like
init() comes handy.
world.recycle is what adds an entity to a pool.
Kinda went overboard on this one, been reading a lot (hurrah summer), but I hope it'll be helpful in the future. Also that I haven't made some horrible, horrible mistake.
Here's a thing if you want to learn from someone who know's what he's talking about.