ios - 在 CCSprite 上检测触摸

标签 ios xcode cocos2d-iphone touch ccsprite

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

我已经像这样定义并添加了我的 Sprite :

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

我已经关注了各种资源,但它们非常模糊,其中大部分 Sprite 都设置在它自己的类中。

提前致谢。

最佳答案

在常规 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 ...
    }
} 

要演示多少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 ...
    }
}

关于ios - 在 CCSprite 上检测触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7883670/

相关文章:

ios - 将评论回复添加到类 "Post"中的字符串数组中

ios - 在这种情况下我如何将按钮居中

swift - Xcode 11 Swift 5 CryptoKit 共享 SymmetricKey

iphone - 2012 年秋季我应该定位哪个 iOS 版本

ios - Cocos3D无法二次显示场景

iphone - 使用 OpenGL ES 进行缩放和滑动

ios - Swift - 导入 Objective-C 给出 "Unknown type name"

ios - 异步下载图像而不阻塞 UI

c++ - cocos2d-x 中所有场景都可以访问的对象

android - 在 cocos2dx 中加载资源,它适用于 android 和 iPhone