检测CCSprite上的触摸

Wil*_*lin 2 xcode touch cocos2d-iphone ios ccsprite

我是cocos2d的新手,请原谅我的无知,但我想知道如何检测精灵何时被触摸并在触摸时调用方法.

我已经定义并添加了我的精灵:

CCSprite *infoButton = [CCSprite spriteWithFile: @"info.png"];
[infoButton setPosition:CGPointMake(450, 290)];
[menuBG addChild:infoButton];
Run Code Online (Sandbox Code Playgroud)

我已经遵循了各种资源,但它们一直很模糊,其中大部分都是精灵设置在自己的类中.

提前致谢.

Lea*_*s2D 11

在常规的Cocos2D中:

-(void) ccTouchesBegan:(NSSet*)touches withEvent:(id)event
{
    CCDirector* director = [CCDirector sharedDirector];
    UITouch* touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:director.openGLView];
    CGPoint locationGL = [director convertToGL:touchLocation];
    CGPoint locationInNodeSpace = [infoButton convertToNodeSpace:locationGL];

    CGRect bbox = CGRectMake(0, 0, 
                             infoButton.contentSize.width, 
                             infoButton.contentSize.height);

    if (CGRectContainsPoint(bbox, locationInNodeSpace))
    {
        // code for when user touched infoButton sprite goes here ...
    }
} 
Run Code Online (Sandbox Code Playgroud)

为了证明Kobold2D在Cocos2D的方法上简化了多少:

-(void) update:(ccTime)delta
{
    KKInput* input = [KKInput sharedInput];
    if ([input isAnyTouchOnNode:infoButton touchPhase:KKTouchPhaseBegan])
    {
        // code for when user touched infoButton sprite goes here ...
    }
}
Run Code Online (Sandbox Code Playgroud)


xua*_*eng 5

为什么不使用CCMenuItemImage?

 CCMenuItemImage* info = [CCMenuItemImage itemFromNormalImage:@"info.png" selectedImage:@"info.png" target:self selector:@selector(pressed:)];
CCMenu* menu = [CCMenu menuWithItems:info, nil];
menu.position = ccp(450,290);
[menuBG addChild:menu];
Run Code Online (Sandbox Code Playgroud)

用户按下按钮时的另一个功能..

-(void)pressed:(id)sender
{
// whatever you would like to do here...
}
Run Code Online (Sandbox Code Playgroud)