Could some one guide me in Context of this post.
http://www.cocos2d-iphone.org/forum/topic/7303#post-42962
how can I use convertToNodeSpace to detect my Sprite is touched?
thanks in advance
A fast, easy to use, free, and community supported 2D game engine
Could some one guide me in Context of this post.
http://www.cocos2d-iphone.org/forum/topic/7303#post-42962
how can I use convertToNodeSpace to detect my Sprite is touched?
thanks in advance
I think this is easy for most people here to do, but I also had a lot of trouble figuring out how to do this. What I do to detect touches on a sprite in my game is something like below.
First, when you place a sprite , add a tag number so you can retrieve the sprite easily later. For example:
[ItemscrollLayer addChild:itemSprite z:Zorder tag:ImageTagNumber]; // use a tag so sprite can be retrieved later
Now , in your ccTouchesBegan method :
CCSprite *itemSprite = (CCSprite*)[ItemscrollLayer getChildByTag:ImageTagNumber]; // get the image sprite
CGPoint SpritePosition = [itemSprite position]; // get the position of the sprite
CGPoint tapPosition = [ItemscrollLayer convertToNodeSpace:[[CCDirector sharedDirector] convertToGL:[touch locationInView:touch.view]]]; // get the tapped position
CGRect SpriteRectangle = CGRectMake(SpritePosition.x-SpriteSize.width/2, SpritePosition.y-SpriteSize.height/2, SpriteSize.width, SpriteSize.height); // get a rectangle of the sprite so it can be compared with the tapped position point
if (CGRectContainsPoint(SpriteRectangle,tapPosition)) // here's where we find out if the sprite was tapped or not
{
// do something here if the sprite was tapped
}
Hope that helps.
This topic has been closed to new replies.