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

我正在用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学习者快速成长!