I am new to Cocos2d and am having problems with one concept. In my game I have pieces scrolling across the screen that the player can grab. This part is easy. I randomly spawn a piece and scroll it with an action. The problem is figuring out what piece the user grabbed. My gut said subclass AtlasSprite but the AtlasSpriteManager wouldn't take the subclass as a child. Am I doing something wrong and/or what is the recommend way to track data about an AtlasSprite?
How to track extra data with an AtlasSprite
(8 posts) (4 voices)-
Posted 2 years ago #
-
All CocosNodes have a void pointer called userData that you can point to whatever you want. Alternatively there is an integer property called tag that you can set to whatever value you want, this could be an index into an array.
Posted 2 years ago # -
userData sounds promising but I can't figure out how to use it. It always returns void.
int i = 99; sp.userData = i; int x = sp.userData;When I run this code x is set to 0.
Posted 2 years ago # -
I subclass AtlasSprite all over the place and have no issues adding it to an AtlasSpriteManager (using 0.8.1 here). Are you sure you are subclassing AtlasSprite and not Sprite?
Posted 2 years ago # -
Thanks Steve. That makes sense. In other words my over simplified test was just that... too over simplified. The userData needs to be set to a pointer not a c-type.
This works.
NSString *str = [NSString stringWithFormat:@"Piece: %i", currentPiece]; sp.userData = str; NSString *str2 = (NSString *) sp.userData; NSLog(@"String2 = %@", str2);I will just make an object to hold all of the data I need to track and it should work the same way. This is what I was planning to do in the first place.
Posted 2 years ago # -
@hactar looks like I had done something wrong in my first test. This seems to be working fine now. The userData is very useful but in this case the subclassing works better.
Thanks everyone for the help. I have been very impressed by cocos2d and look forward to learning more about it.
Posted 2 years ago # -
Is subclassing AtlasSprite the way to go for characters/objects in a game? If so, would you handle all the collision and animation behaviors as well?
Posted 2 years ago #
Reply
You must log in to post.