我正在用cocos2d开发一款iPhone2d游戏,其中设置有很多小精灵。我想通过触摸两个类似的精灵的方式,将它们两个都隐藏起来,我如何能够实现这种效果呢?
原问题:How can I detect touch in cocos2d?
PHPz2017-04-21 11:21:24
Answer: Jonas
(Best answer)
In the layer containing sprites, you need to enter:
self.isTouchEnabled = YES;
Then, you can use the same event in the UIView, but the method they are called is different:
- (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.
}
Answer: Terence
To achieve this effect, you can set a bounding box for the sprites. In the following code, I place all sprites in NSMutableArray and check whether they are within the bounding box. At the same time, make sure that the touch has been initialized. Operation:
- (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;
}
Answer: David Higgins
Based on Jonas's answer, I made further improvements:
- (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;
}
}
You may need to adjust the x/y position to ensure the "center position" of the sprite.
Answer: John
David's code will cause error messages on Cocos 0.7.3 and 2.2.1, so I used CGRectMake instead of CGMakeRect and used [touch locationInView:touch.view] to correct the [touch location] error:
- (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;
}
}