开发者

Cocos2D sprite constrained to screen

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:

float maxX = winSize.width - selSprite.contentSize.width/2;
float minX = selSprite.contentSize.width/2;
float maxY = ...;
float minY = ...;

if (selSprinte.position.x > maxX)
{
    selSprite.position = ccp(maxX, selSprite.position.y);
}
else if (selSprinte.position.x < minX)
{
    selSprite.position = ccp(minX, selSprite.position.y);
}


if (selSprinte.position.y > maxY)
{
    selSprite.position = ccp(selSprite.position.x, maxY);
}
else if (selSprinte.position.y < minY)
{
    selSprite.position = ccp(selSprite.position.x, minY);
}

and add the same code for y.


I have a sprite which is larger in size than the screen size. I used this:

node.position = CGPointMake(MIN(MAX(size.width  - node.contentSize.width /2,node.position.x), node.contentSize.width  / 2),
                            MIN(MAX(size.height - node.contentSize.height/2,node.position.y), node.contentSize.height / 2));

Using this code, my sprite corner was either outside the screen or at the edge of the screen which helped me to see my complete image by scrolling it.

Here:

node = CCSprite
size = [[CCDirector sharedDirector] winSize]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜