I'm having a really hard time getting something as simple as detecting touch on a sprite to work... Can anybody help? I'm trying to create a method as a category for CCSprite that given a point or touch will return YES if the point is within the sprite, NO if it isn't.
At the moment I have one implementation that seems to work when the sprite is not part of a cropped texture from Zwoptex (ie. the image used for sprite was not trimmed)
CGPoint point = [touch locationInView:[touch view]];
point = [[CCDirector sharedDirector] convertToGL: point];
CGRect spriteRect = self.textureRect;
spriteRect.origin = ccpAdd(ccpSub(self.positionInPixels, self.anchorPointInPixels), self.offsetPositionInPixels);
return CGRectContainsPoint(spriteRect, point);
I have found though that this does not work if the sprite was trimmed in the original texture. This variation seemed to do the trick
CGRect spriteRect = self.textureRect;
spriteRect.origin = ccpAdd(self.offsetPositionInPixels, self.positionInPixels);
return CGRectContainsPoint(spriteRect, [self convertTouchToNodeSpaceAR:touch]);
But now I have another set of sprites from a frame cache that do not seem to like this! They are trimmed and I can't see any difference from the sprites used with the code above. Can som开发者_开发问答eone shed some light on the meaning of convertTouchToNodeSpaceAR:? I'm sure the problem lies in my ignorance and that there is a common elegant way of doing this in the Cocos2d framework...
The problem is probably CGRectContainsPoint();
. I was having the same issue for a while and I suspect that the rect and the points we were comparing were not translated to the same point system yielding negative results.
Solutions:
- Make a method / define that can correctly convert the point systems between each other.
- What I did: Create a grid class that tracks a sprites position on the grid and translate touches to the points on the grid.
Option 1 may make more sense for your needs, but I needed to reference sprites positions relative to each other quite often so it made sense to me.
If you want to go with option 1, I would suggest getting some NSLogs and printing out a point of the rect and the point you are comparing against and figure out what the different is.
精彩评论