2012-06-26 92 views
0

我在Cocos2d中創建了一個用於滾動背景的代碼來創建相機的效果,但是我不能防止相機超出背景邊緣。我的背景是1440 * 1080的圖像。我的代碼是:我如何定義邊緣?

+(id) scene 

{ 
    CCScene* scene = [CCScene node]; 
    TileDemo* layer = [TileDemo node]; 
    [scene addChild: layer]; 
    return scene; 
} 

-(id) init 

{ 

    if ((self = [super init])) 

    { 
     self.isTouchEnabled = YES; 
     CCSprite *Nivel1 = [CCSprite spriteWithFile:@"Nivel1.png"]; 
     Nivel1.position = ccp(0.5f, 0.5f); 
     [self addChild:Nivel1 z:0 tag:1]; 
    } 

    return self; 

} 

-(void) dealloc 

{ 
    [super dealloc]; 

} 

-(void) registerWithTouchDispatcher 

{ 

    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; 

} 

-(BOOL) ccTouchBegan:(UITouch*)touch withEvent:(UIEvent*)event 

{ 
    return YES; 
} 

-(void) ccTouchEnded:(UITouch*)touch withEvent:(UIEvent*)event 

{ 

} 

-(void) ccTouchCancelled:(UITouch*)touch withEvent:(UIEvent*)event 

{ 

} 

-(void) ccTouchMoved:(UITouch*)touch withEvent:(UIEvent*)event 

{ 
    CGPoint touchLocation = [touch locationInView: [touch view]]; 
    CGPoint prevLocation = [touch previousLocationInView: [touch view]]; 

    touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation]; 
    prevLocation = [[CCDirector sharedDirector] convertToGL: prevLocation]; 

    CGPoint diff = ccpSub(touchLocation,prevLocation); 

    CCNode* node = [self getChildByTag:1]; 
    CGPoint currentPos = [node position]; 
    [node setPosition: ccpAdd(currentPos, diff)]; 
} 

@end 

回答

0

你算算你的精靈的最大值和最小值posiible位置,並檢查它在你的touchMoved:withEvent:方法。在我看來,當您的精靈的anchorPoint位於(0.f,0.f)而不是標準(0.5f,0.5f)時,計算這些值會更容易。那麼你的位置將是

CGPoint maxPos = ccp(0.f, 0.f); 
CGPoint minPos = ccp((spriteWidth - screenWidth) * (-1), (spriteHeight - screnHeight) * (-1)); 

然後在設置它之前檢查你的精靈的新位置是否在有效範圍內。