我的图层中有15个精灵。我将这些精灵添加到可变数组中我希望使用ccTouchesMoved
移动单个精灵。当触摸结束ccTouchesEnded
精灵移回其起点或其原点。
我的编码:
if( (self=[super init])) {
collection=[[NSMutableArray alloc]init];
CCLayer *base=[CCSprite spriteWithFile:@"Base.png"];
base.position=ccp(512,384);
[self addChild:base];
x=0;
for(int i=1;i<=7;i++)
{
CCSprite *hole=[CCSprite spriteWithFile:@"ball.png"];
hole.position=ccp(140+x,318);
hole.tag=i;
[self addChild:hole];
hole.visible=YES;
[collection addObject:hole];
x=x+75;
}
self.isTouchEnabled=YES;
}
return self;
}
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
CGPoint location=[touch locationInView:[touch view]];
location=[[CCDirector sharedDirector]convertToGL:location];
location=[self convertToNodeSpace:location];
p=location;
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"count:%i",[collection count]);
UITouch *touch=[touches anyObject];
CGPoint location=[touch locationInView:[touch view]];
location=[[CCDirector sharedDirector]convertToGL:location];
location=[self convertToNodeSpace:location];
for(CCSprite *s in collection)
{
if(CGRectContainsPoint([s boundingBox], location))
s.position=ccp(location.x,location.y);
}
}
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
for(CCSprite *s in collection)
{
s.position=p;
}
}
当我移动一个精灵时,在图层上也可以看到其他精灵,而不是隐藏。 请帮我代码。
答案 0 :(得分:0)
for(CCSprite *s in collection)
{
if(CGRectContainsPoint([s boundingBox], location))
s.position=ccp(location.x,location.y);
}
由于你所有的精灵都在同一个位置,上面的代码正在移动那个位置的所有精灵。
for(CCSprite *s in collection)
{
if(CGRectContainsPoint([s boundingBox], location))
{
s.position=ccp(location.x,location.y);
break;
}
}
一旦检测到第一个sprite,上面的代码就会突破循环,因此只应移动数组中的第一个sprite。
不确定这是否正是您想要的,但希望这会有所帮助。
----修改
我个人会做的是为精灵设一个实例变量。
CCSprite * touchedSprite;
并执行以下操作......
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
CGPoint location=[touch locationInView:[touch view]];
location=[[CCDirector sharedDirector]convertToGL:location];
location=[self convertToNodeSpace:location];
for((CCSprite * sprite in collection)
{
if(CGRectContainsPoint([sprite boundingBox], location))
{
touchedSprite = sprite;
p = sprite.position;
break;
}
}
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"count:%i",[collection count]);
UITouch *touch=[touches anyObject];
CGPoint location=[touch locationInView:[touch view]];
location=[[CCDirector sharedDirector]convertToGL:location];
location=[self convertToNodeSpace:location];
touchedSprite.position = location;
}
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
touchedSprite.position = p;
}
我没有测试代码所以我不确定它是否只能通过复制和粘贴工作,但我认为这会给你一个正确的想法。显然有其他方法可以做到这一点,但我认为如果你要对被触摸的精灵做一堆东西最简单。