在这里有一个问题。我在我的(id)init函数中创建了几个sprite(带标签),然后只是试图检测哪个sprite被触摸了?我的init函数的代码片段粘贴在下面。
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"blue_sheet.plist"];
//create a sprite batch node
CCSpriteBatchNode *TrainerSprites = [CCSpriteBatchNode batchNodeWithFile:@"blue_sheet.png"];
[self addChild:TrainerSprites z:1];
//create a sprite from that node
CCSprite *Horse = [CCSprite spriteWithSpriteFrameName:@"horse_blue.png"];
[TrainerSprites addChild:Horse z:1 tag:1];
//Horse.position = ccp(winSize.width/5, winSize.height/2);
[Horse setScaleX: 138.5/Horse.contentSize.width];
[Horse setScaleY: 80/Horse.contentSize.height];
//create a sprite from that node
CCSprite *Cow = [CCSprite spriteWithSpriteFrameName:@"cow_blue.png"];
[TrainerSprites addChild:Cow z:1 tag:2];
//Cow.position = ccp(winSize.width/2, winSize.height/2);
[Cow setScaleX: 126/Cow.contentSize.width];
[Cow setScaleY: 100/Cow.contentSize.height];
Horse.position = ccp(4*winSize.width/5, winSize.height/2);
Cow.position = ccp(winSize.width/5, winSize.height/2);
CGRect pos1 = CGRectMake(Cow.position.x, Cow.position.y, 200, 100);
CGRect pos2 = CGRectMake(Horse.position.x, Horse.position.y, 200, 100);
self.touchEnabled = YES;
一切看起来都很好......精灵出现在他们想要的地方。当我触摸屏幕上的任何地方时,我的ccTouchBegan功能会触发。没有看到CGRect发生任何事情,我想我需要确定由指定标签触发的那个。是的,我知道我缺少代码,我无法在任何地方找到好的文档如何做这个看似基本的ios功能。我假设“精灵触摸检测”代码应该驻留在ccTouchBegan函数中?任何帮助或指导真诚地感谢。 :)
答案 0 :(得分:0)
检测精灵触摸你可以使用这个
在.h部分声明CCSprite *Cow
并在.m部分使用此
在init方法
//create a sprite from that node
Cow = [CCSprite spriteWithSpriteFrameName:@"cow_blue.png"];
[TrainerSprites addChild:Cow z:1 tag:2];
//Cow.position = ccp(winSize.width/2, winSize.height/2);
[Cow setScaleX: 126/Cow.contentSize.width];
[Cow setScaleY: 100/Cow.contentSize.height];
触摸开始方法
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch =[touches anyObject];
CGPoint location=[touch locationInView:[touch view]];
location =[[CCDirector sharedDirector] convertToGL:location];
if (CGRectContainsPoint( [Cow boundingBox], location)) {
/* CCScene *scene = [CCScene node];
[scene addChild:[ClassicScene node]];
[[CCDirector sharedDirector] replaceScene:scene];*/
}
}
答案 1 :(得分:0)
另一种方法可能是继承CCSprite并实现TargetedTouchDelegate。
类似的东西:
@interface AnimalSprite:CCSprite<CCTargetedTouchDelegate>
这种方法的优点是你不必做很多事情,如果&#34;检查要添加精灵的图层。该链接提供了必须在orer中实现的方法,以实现协议以及在何处以及如何向触摸调度程序注册。