objective-c - 如何在Cocos2d中实现精灵的触摸消失?
怪我咯
怪我咯 2017-04-21 11:19:24
0
1
608

我正在用cocos2d开发一款iPhone2d游戏,其中设置有很多小精灵。我想通过触摸两个类似的精灵的方式,将它们两个都隐藏起来,我如何能够实现这种效果呢?

原问题:How can I detect touch in cocos2d?

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回覆 (1)
PHPzhong

答: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; } }
    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!