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
4

1 回答 1

0

你必须计算你的精灵的最大和最小可能位置并在你的touchMoved:withEvent:方法中检查它。在我看来,当你的 sprite 的 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));

然后在设置之前检查你的精灵的新位置是否在有效范围内。

于 2012-06-26T10:38:49.300 回答