我正在用cocos2d开发一款iPhone2d游戏,其中设置有很多小精灵。我想通过触摸两个类似的精灵的方式,将它们两个都隐藏起来,我如何能够实现这种效果呢?
原问题:How can I detect touch in cocos2d?
PHPz2017-04-21 11:21:24
答:Jonas
(最佳答案)
在含有精靈的layer中,你需要輸入:
self.isTouchEnabled = YES;
然後,你可以使用在UIView中的相同event,但是它們被呼叫的方法不同:
- (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.
}
答:Terence
想要實現這種效果,可以為精靈設定定界框(bounding box),在下述程式碼中,我將所有精靈都置於NSMutableArray中,並檢查它們是否處於定界框內,同時要保證已經初始化觸摸操作:
- (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;
}
答:David Higgins
根據Jonas的回答,我又做了進一步的改進:
- (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;
}
}
你可能需要調整x/y的位置,確保精靈的「中心位置」。
答:John
David的程式碼在Cocos 0.7.3和2.2.1上,會出現錯誤訊息,所以我用CGRectMake取代CGMakeRect,用[touch locationInView:touch.view]修正了[touch location]的錯誤:
- (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;
}
}