Hello. I want to convert some sprites in buttons, but im not sure how to do it.
I know how to add Sprites, but not to detect touches in them and then runing an action
Thanks in advance
A fast, easy to use, free, and community supported 2D game engine
Hello. I want to convert some sprites in buttons, but im not sure how to do it.
I know how to add Sprites, but not to detect touches in them and then runing an action
Thanks in advance
You need to add code in your touch callback methods to determine where the user is touching in relation to the placement of your sprites. For instance if your sprite is a square, you could quickly check to see if the touch occurs within a rectangle the size of your sprite.
im newbie, so this is kind of difficult to me. Can you post a really quick example please. Maybe is easier to understand like that
Here's a sample. Just replace the ractangle bits with the position and size of the sprite you want to act as a button.
- (BOOL) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if(touch) {
CGPoint location = [touch locationInView:[touch view]];
// touches are always in portrait coordinates, which need to be converted to the current orientation
CGPoint convertedPoint = [[Director sharedDirector] convertToGL:location];
// create rectangle (you can base it on your sprite coordinates)
// CGRectMake(x, y, width, height)
CGRect rect = CGRectMake(100, 100, 50, 50);
if (CGRectContainsPoint(rect, convertedPoint)) {
return YES;
}
}
return NO;
}a question. I have to put in the CGRectContainsPoint method, what i want to happen when the user taps in the sprite?
Okay, it doesnt work. I paste/copy your code, and put an NSLOG()
Nothing is showing in the console
Edit: I forgot to put in the init
self.isTouchEnabled = YES;
Now it works
Thanks really
Happy New Year
To answer your question:
a question. I have to put in the CGRectContainsPoint method, what i want to happen when the user taps in the sprite?
You would put your "actions" in that if/else block:
...
CGRect rect = CGRectMake(100, 100, 50, 50);
if (CGRectContainsPoint(rect, convertedPoint)) {
// PUT ACTION CODE HERE
return YES;
}
...You must log in to post.