触摸时精灵错误移动

时间:2013-01-30 05:42:34

标签: iphone objective-c cocoa-touch cocos2d-iphone

我的场景中有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;
 }
}

1 个答案:

答案 0 :(得分:1)

你可以这样做:

在界面.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;
    }
}