iPhone中cocos2D和触摸检测的问题

12

我就是不明白。

我在iPhone/Pod上使用cocos2d来开发一个小游戏。这个框架非常棒,但是我在触摸检测方面失败了。我读到说你只需要在继承CocosNode的类的实现中重写正确的函数(例如“touchesBegan”)即可。但它不起作用。我可能做错了什么?

这是要翻译的内容:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{NSLog(@"tickle, hihi!");}

我完全弄错了吗?

7个回答

11

Layer 是唯一一个能够接收触摸事件的 cocos2d 类。

其中的诀窍是:所有 Layer 实例都会被依次传递触摸事件,因此您的代码必须处理这一点。

我是这样做的:

-(BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
CGPoint cLoc = [[Director sharedDirector] convertCoordinate: location];

float labelX = self.position.x - HALF_WIDTH;
float labelY = self.position.y - HALF_WIDTH;
float labelXWidth = labelX + WIDTH;
float labelYHeight = labelY + WIDTH;

if( labelX < cLoc.x &&
    labelY < cLoc.y &&
    labelXWidth > cLoc.x &&
    labelYHeight > cLoc.y){
        NSLog(@"WE ARE TOUCHED AND I AM A %@", self.labelString);
        return kEventHandled;
    } else {
        return kEventIgnored;
    }

}

请注意,cocos2d库具有“ccTouchesEnded”实现,而不是苹果标准。 它允许您返回一个BOOL值,指示您是否处理了事件。

祝你好运!


3
你可以让任何CCNode类接收触摸事件!例如使用:[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO]; - CodeSmile
1
类必须实现两个TouchDelegate协议中的一个。 - CodeSmile

5
你是否已经将这个添加到你的图层初始化方法中?
    // isTouchEnabled is an property of Layer (the super class).
    // When it is YES, then the touches will be enabled
    self.isTouchEnabled = YES;

    // isAccelerometerEnabled is property of Layer (the super class).
    // When it is YES, then the accelerometer will be enabled
    self.isAccelerometerEnabled = YES;

3
为了检测触摸事件,您需要从UIResponder(UIView也是如此)派生子类。我不熟悉cocos2D,但快速查看文档发现CocosNode没有从UIResponder派生。
进一步调查后,看起来Cocos团队创建了一个从CocosNode派生的Layer类。该类实现了触摸事件处理程序。但这些都以cc为前缀。
请参见http://code.google.com/p/cocos2d-iphone/source/browse/trunk/cocos2d/Layer.h 还可以查看menu.m代码和以下博客文章获取更多信息:

http://blog.sapusmedia.com/2008/12/cocos2d-propagating-touch-events.html


3

maw,CGPoint结构体的成员x和y是浮点数。使用@"%f"来格式化浮点数以用于printf/NSLog。


3

1
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

        //Add a new body/atlas sprite at the touched location
        CGPoint tapPosition;
        for( UITouch *touch in touches ) {
            CGPoint location = [touch locationInView: [touch view]];

            tapPosition = [self convertToNodeSpace:[[CCDirector sharedDirector] convertToGL:location]];     // get the tapped position





    }
}

我觉得这可能会对你有所帮助……


0

-让您的场景符合协议CCTargetedTouchDelegate -将此行添加到您场景的init中:

[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];

-实现以下函数:

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
 {
   return  YES;
 }
 -(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
  {
    //here touch is ended
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接