如何检测cocos2d中的触摸?

Md *_*din 11 iphone objective-c cocos2d-iphone

我正在使用cocos2d为iPhone开发一款2D游戏.

我在游戏中使用了很多小精灵(图像).我想触摸两个相似类型的精灵(图像),然后两个精灵(图像)将被隐藏.

如何检测特定精灵(图像)中的触摸?

小智 27

更好的方法是实际使用精灵本身的边界框(这是一个CGRect).在这个示例代码中,我将所有精灵放在NSMutableArray中,并且我简单地检查精灵触摸是否在边界框中.确保在init中打开触摸检测.如果你注意到我也通过返回YES(如果我使用触摸)或否(如果我不这样做)接受/拒绝图层上的触摸

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event 
{
  CGPoint location = [self convertTouchToNodeSpace: touch];

  for (CCSprite *station in _objectList)
  {
    if (CGRectContainsPoint(station.boundingBox, location))
    {
      DLog(@"Found sprite");
      return YES;
    }
  }

  return NO;
}
Run Code Online (Sandbox Code Playgroud)

  • 我同意这更好,因为它非常干净 (2认同)

Dav*_*ins 23

按照乔纳斯的指示,再添加一点......

- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
   UITouch* touch = [touches anyObject];
   CGPoint location = [[[Director sharedDirector] convertCoordinate: touch.location];
   CGRect particularSpriteRect = CGMakeRect(particularSprite.position.x, particularSprite.position.y, particularSprite.contentSize.width, particularSprite.contentSize.height);
   if(CGRectContainsPoint(particularSpriteRect, location)) {
     // particularSprite touched
     return kEventHandled;
   }
}
Run Code Online (Sandbox Code Playgroud)

您可能需要调整x/ya以适应Cocos中的"居中定位"

  • +1教我CGRectContainsPoint在CocosLand中工作. (2认同)
  • 我喜欢CGRectContainsPoint; 但是,CGMakeRect应该是CGRectMake,除此之外,我只会使用:CGRect specificSpriteRect = [specialSprite boundingBox]; (2认同)
  • cocos2d中没有convertCoordinate和touch.location (2认同)

Jon*_*nas 16

在包含您的精灵的图层中,您需要说:

self.isTouchEnabled = YES;
Run Code Online (Sandbox Code Playgroud)

然后你可以使用你在UIView中使用的相同事件,但它们的命名有点不同:

- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
   UITouch* touch = [touches anyObject];
  //in your touchesEnded event, you would want to see if you touched
  //down and then up inside the same place, and do your logic there.
}
Run Code Online (Sandbox Code Playgroud)

  • 我不确定你是什么意思......哪种特别的触摸? (5认同)

Joh*_*ohn 7

@david,你的代码有一些关于cocos 0.7.3和2.2.1的拼写错误,特别是CGRectMake而不是CGMakeRect,[touch location]现在是[touch locationInView:touch.view].

这就是我做的:

- (BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch * touch = [touches anyObject];

    CGPoint location = [[Director sharedDirector] convertCoordinate: [touch locationInView:touch.view]];
    CGRect myRect = CGRectMake(sprite.position.x, sprite.position.y, sprite.contentSize.width, sprite.contentSize.height);


    if(CGRectContainsPoint(myRect, location)) {
        // particularSprite touched
        return kEventHandled;
    }
}
Run Code Online (Sandbox Code Playgroud)