Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

azg442

macrumors newbie
Original poster
May 10, 2009
12
0
In cocos2d how would you detect a touch on an image? I'm having a lot of trouble with this so thanks in advance!
 
Assuming your UIImage is in a UIImageView which is a subclass of UIView which is a subclass of UIResponder, you can use touchesBegan:withEvent:

Or you can define a UIButton using an image for it and then use UIControl's (it's superclass) addTarget:action:forControlEvents:
 
When you create the MenuItemImage you create it with a target and a selector, right?

Code:
+(id)itemFromNormalImage:selectedImage:disabledImage:target:selector:

The menu items don't do anything though unless they are added to a menu afterwards

Heres an example of what would work

Code:
-(void)onEnter
{
     Sprite * ButtonNormal = [Sprite spriteWithFile:@"button1normalimage.png"];
     Sprite * ButtonSelected = [Sprite spriteWithFile:@"button1selected.png"];
     Sprite * ButtonDisabled = [Sprite spriteWithFile:@"button1disabled.png"];

     MenuItemImage * Button1 = [MenuItemImage itemFromNormalImage:ButtonNormal selectedImage:ButtonSelected disabledImage:ButtonDisabled target:self selector:@selector(buttonTouched:)];

     menu * TheMenu = [Menu menuWithItems: Button1, nil];
     [TheMenu alignItemsVertically];
     [self addChild:TheMenu z:1];
}

-(void)buttonTouched:(id)Sender
{
     // Do something as the button was touched
}

Just as a side note cocos2d is VERY picky about the methods that you use as selectors, you ALWAYS have to have an argument of type id otherwise cocos2d will just ignore the selector and touching the menu item will do nothing.
 
What im trying to do is put a touches began in a void. But this thats not working.
 
What do you mean by putting touches began in a void? :confused:

If you are using a MenuItemImage i suggest you read over what mccannmarc has written as his example shows exactly how to handle touches with MenuItems.

if you want to use touches on a layer you should use the cocos method of handling touches which looks like:
Code:
-(BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
       return(kEventHandled);
}

please note that this method can only be used on layers and the layer must have its isEnabled bool set to True/Yes.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.