0

我的场景中有 20 个精灵,已添加到NSMutableArray. 我的问题是,当我将一个精灵拖到另一个上时,另一个也会移动。如何限制未触及的精灵的移动?

请帮我写代码(我是 Cocos2d 的新手)。

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)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);
    return;
 }
}
4

1 回答 1

1

你可以这样做:

在 interface .h 文件中声明它

CCSprite *mSpriteOnHand;
CGPoint mLastPos;

在 init 内部将其赋值为 nil。

mSpriteOnHand = nil;

在 touchesBegan 方法中像这样检查

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *myTouch = [touches anyObject];
    CGPoint location = [myTouch locationInView:[myTouch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];


    for(CCSprite *s in collection)
    {
        if(CGRectContainsPoint([s boundingBox], location))
        {
            mLastPos = s.position;
            s.position=ccp(location.x,location.y);

            mSpriteOnHand = s;
            break;
        }
    }

}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch=[touches anyObject];
    CGPoint location=[touch locationInView:[touch view]];
    location=[[CCDirector sharedDirector]convertToGL:location];
    location=[self convertToNodeSpace:location];

    if(mSpriteOnHand)
    {
        mSpriteOnHand.position = location;
    }
}



- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(mSpriteOnHand)
    {
         mSpriteOnHand.position = mLastPos;
         mSpriteOnHand = nil;
    }
}
于 2013-01-30T08:09:54.447 回答