我已经制作了一个用于在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 :(得分:0)
您必须计算精灵的最大和最小位置,并在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));
然后在设置之前检查你的精灵的新位置是否在有效范围内。