I’m having a problem with Cocos2D. I’m trying to have a sprite movable on screen (which I’ve been able to do), but stop it from being clipped by the edge of the screen.
If I’m correct, sprites are imported to the layer as rectangles (spriteWithFile:@”filename.ext” rect:CGRectMake(0, 0, X, Y);).
The only thing I’ve been able to figure out so far is to setup my code to detect if the rectangle of the sprite has gone outside of the “background” layer, and adjust it accordingly if it does.
This is what I have so far, but it doesn’t seem to be working correctly:
- (void)panForTranslation:(CGPoint)translation {
CGSize winSize = [CCDirector sharedDirector].winSize;
float maxX = winSize.width - selSprite.contentSize.width/2;
float minX = selSprite.contentSize.width/2;
float maxY = winSize.height - selSprite.contentSize.height/2;
float minY = selSprite.contentSize.height/2;
if (selSprite.position.x > maxX)
{
selSprite.position = ccp(maxX, selSprite.position.y);
}
else if (selSprite.position.x < minX)
{
selSprite.position = ccp(minX, selSprite.position.y);
}
if (selSprite.position.y > maxY)
{
selSprite.position = ccp(selSprite.position.x, maxY);
}
else if (selSprite.position.y < minY)
{
selSprite.position = ccp(selSprite.position.x, minY);
}
CGPoint newPos = ccpAdd(selSprite.position, translation);
selSprite.position = newPos;
}
Is there something completely obvious that I’m missing? My sprites keep moving off screen if I drag them, and I can’t figure it out for the life of me.
Try this:
and add the same code for y.