Jump to content

get sprite by id?


ethan.sletteland
 Share

Recommended Posts

Hey all,

Sorry if this is addressed elsewhere, but I RTFM'ed and I can't find it. What is best practice for getting a handle for a sprite on the stage? I'm working on a sidescroller, using tiled and the import and loop technique described in this tutorial:

http://gamedevacademy.org/html5-phaser-tutorial-top-down-games-with-tiled

At some point I want my player to collide with one sprite (a switch), and then I want to change the state of another sprite (a door). My thought is to do this by creating a global dictionary object and registering each sprite with it as I create them, and I can certainly do that, but I feel like I might be recreating a wheel here. Is there some kind of getSpriteById() that I'm too dumb to see?

Link to comment
Share on other sites

The way I'd do it:

Extend Phaser.Sprite to create the switch; inside the Switch class (or the name you choose) make a reference to the door and assign it when creating that switch. Then you'll be able to access that door using that reference.

Link to comment
Share on other sites

you can create a global object like this: 

var registry = { door:{}};// save reference like thisregistry.door = game.add.sprite(0,0,"door");

You can totally do that, but carefull not to overdo it, because it will be difficult to manage. Also in monos' answer is correct. However there is no fast way to search by ID, although you can reference by index, if your door is inside a group and its the 1st child you can do 

var door = myObjects.getChildAt(0);

Or if you set that your first door to encounter is the only one with the "alive = true" property set, you can do:

var door = myObjects.getFirstAlive();
Link to comment
Share on other sites

 

you can create a global object like this: 

var registry = { door:{}};// save reference like thisregistry.door = game.add.sprite(0,0,"door");

You can totally do that, but carefull not to overdo it, because it will be difficult to manage. Also in monos' answer is correct. However there is no fast way to search by ID, although you can reference by index, if your door is inside a group and its the 1st child you can do 

var door = myObjects.getChildAt(0);

Or if you set that your first door to encounter is the only one with the "alive = true" property set, you can do:

var door = myObjects.getFirstAlive();

What I ended up using was similar, but a little more dynamic.

if(element.properties.hasOwnProperty('trigger')){    objects.trigger[element.properties.trigger] = sprite;}

where element is the loop entry, sprite is the handle for the newly created sprite, and trigger is arbitrary attribute I added in tiled. Thanks!

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...