扫码关注官方订阅号
84669人学习
65727人学习
82984人学习
467778人学习
498837人学习
471966人学习
256484人学习
152542人学习
224170人学习
139536人学习
81804人学习
85022人学习
11944人学习
20001人学习
60816人学习
5487人学习
15007人学习
2150人学习
6980人学习
194925人学习
359900人学习
1142人学习
19058人学习
3206人学习
180550人学习
48569人学习
17603人学习
40936人学习
1049人学习
750人学习
32909人学习
我正在用cocos2d开发一款iPhone2d游戏,其中设置有很多小精灵。我想通过触摸两个类似的精灵的方式,将它们两个都隐藏起来,我如何能够实现这种效果呢?
原问题:How can I detect touch in cocos2d?
走同样的路,发现不同的人生
答: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; } }
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
扫描下载App
Copyright 2014-2024 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号
精品班
技术支持
技术咨询
学习群
会员优惠
返回顶部
答:Jonas
(最佳答案)
在含有精灵的layer中,你需要输入:
然后,你可以使用在UIView中的相同event,但是它们被调用的方法不同:
答:Terence
想要实现这种效果,可以给精灵设置定界框(bounding box),在下述代码中,我将所有精灵都置于NSMutableArray中,并检查它们是否处于定界框内,同时要保证已经初始化触摸操作:
答:David Higgins
根据Jonas的回答,我又进行了进一步的完善:
你可能需要调整x/y的位置,保证精灵的“中心位置”。
答:John
David的代码在Cocos 0.7.3和2.2.1上,会出现错误信息,所以我用CGRectMake替代CGMakeRect,用[touch locationInView:touch.view]纠正了[touch location]的错误: