【问题标题】:Detect touch *anywhere on the screen* in cocos2d?在 cocos2d 中检测触摸*屏幕上的任何位置*?
【发布时间】:2010-11-13 13:06:12
【问题描述】:

我真的很抱歉,我知道有几个关于 cocos2d 触摸检测的问题(包括this 回答,这对我有很大帮助),但我无法让它们中的任何一个工作。我会评论我链接的答案,而不是问我自己的问题,但我没有足够的代表离开 cmets。

我要做的就是在用户点击屏幕上的任意位置时立即停止动画。

到目前为止,这是我的代码:

- (BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touches Began");
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView: [touch view]];
    location = [[Director sharedDirector] convertCoordinate: location];

    CGRect mySurface = (CGRectMake(100, 100, 320, 480));
    if(CGRectContainsPoint(mySurface, location)) {
        NSLog(@"Event Handled");
        return kEventHandled;
        [[Director sharedDirector] stopAnimation];
       }
     return kEventIgnored;
     NSLog(@"Event Ignored");

}

我已经尝试了BOOLvoidccTouchesBegantouchesBegan,在一个层文件和一个 cocosNode 文件中,以及许多其他的东西。什么都没发生。日志中没有显示任何内容,动画继续以它快乐的小路前进。我做错了什么?

【问题讨论】:

    标签: iphone objective-c cocos2d-iphone ipod-touch


    【解决方案1】:

    主要问题是[[Director sharedDirector] stopAnimation];return kEventHandled; 之后而不是在它之前。 return 一被调用就退出函数,所以它之后的任何东西都不会被调用。

    我面前没有我的 mac 来检查你的其余代码,但它看起来很好,所以我猜这是主要问题。如果您甚至没有看到NSLog(@"Touches Began");,那么您需要确保您在扩展LayerCocosNode 中执行此操作。

    另一个有用的东西(一旦你看到触摸)是NSStringFromCGPoint 函数,它允许您轻松显示和调试CGPoint 中的值,因此您可以执行以下操作:

    NSLog(@"This layer was touched at %@", NSStringFromCGPoint(location));
    

    【讨论】:

    • 我对扩展的含义一头雾水。我应该做@interface GameLayer : Layer 还是@interface Node : CocosNode
    • 我认为您的代码是正确的,只是您必须将 stopAnimation 行移到返回行上方,并且与最后一个 NSLog 相同。否则,将永远无法访问该代码。所以先解决这个问题。
    • 应该是@interface GameLayer : Layer,因为Layer已经扩展了CocosNode。此外,在 init 方法中,您需要设置 self.isTouchEnabled = YES; 查看这篇文章以获取更多信息:stackoverflow.com/questions/377785/…
    猜你喜欢
    • 2014-12-09
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多