slycrel/JSTileMap

Access Sprite created for Object in ObjectGroup

Closed this issue · 4 comments

JSTileMap correctly creates sprites that correspond to objects placed in an object group but then there is no way to easily pull them out. The sprite is not in some way associated with the dictionary that represents the object.

Example - I have an object group called "stuff". Inside it I create an object called "player" based on a tile. I load the TMX with JSTileSet. "player" is correctly displayed in the correct location. I now want to somehow get a hold of player's sprite. I pull the "stuff" TMXObjectGroup. I pull the NSDictionary for "player". There is no association with the sprite being displayed on the screen for player.

Here's the code where that sprite is created (lined 747-750 in latest public commit) and its reference is just thrown away:
SKSpriteNode* sprite = [SKSpriteNode spriteNodeWithTexture:texture]; sprite.position = pt;
sprite.zPosition = baseZPosition + ((map.zOrderCount - objectGroup.zOrderCount) * zOrderModifier);
[map addChild:sprite];

PS Thanks for putting out this library. It's really great, and I'm using it successfully from Swift with the obj-c bridge.

You can use the objectGroup's method objectNamed: to get a specifically named object from the tmx file. However you raise a good point that you may want access to the sprite itself. You can add name for them with code something like this, assuming the object has a name already.

    sprite.name = obj[@"name"];

This does have some caveats (i.e. you have to worry about your own name collisions), but generally can be used here. If you want some sort of automatic naming scheme then I'd suggest creating a method on the objectGroup that returned a name for each object. Creating the name would look something like this:

[NSString stringWithFormat:@"%@%@%@", objectGroup.groupName, obj[@"x"], obj[@"y"]];

I'll push the top change which should be good enough for most cases. Thanks for reporting this, and I hope that helps some.

Thanks for the update. Ideally, it would go the other way around -
obj[@"sprite"] = sprite
But I see obj is not mutable at that point in the code and I guess we'd be worried about collisions? It could be something special like __sprite or something as a key. Thanks for the quick reply and pushing the fix.

You can use SKNode's method childNodeWithName: to find the sprite using the name that is now set.

I understand that, I was more just saying from an abstraction point of view, it kind've makes sense for the sprite to belong to the object since that's how it's set up in Tiled/the tmx. Anyway, this works well and thanks again!