Tuesday, June 7, 2011

Positioning scaled CCLayer to center it on player.

I am developing a game in Cocos2D. Two days ago I've been working on my game that is Cocos2D powered and spent some time working on simple task - positioning CCLayer the way my game hero will be always in the center of the screen, on any scale level. I didn't take into account world borders because in my game player shouldn't see it anyway.

Here is the code snippet for changing CCLayer position.

Somewhere in the init method we declare _origin, that points on the center of the screen.
// ask director the window size
CGSize _winSize = [[CCDirector sharedDirector] winSize];
CGPoint _origin = CGPointMake(_winSize.width/2.0, _winSize.height/2.0);


Then we use CCLayer's convertToWorldSpace: method to get "world space" coordinates of the player and center of the screen, then find the difference between these two points, and finally place gameLayer at position where the player object will be on the center of the screen.


- (void)setViewpointCenter:(CGPoint)playerPos {

/* Convert object point and origin point to WorldSpace,
then sub it. */
CGPoint wPlayer = [gameLayer convertToWorldSpace:playerPos];
CGPoint wOrigin = [gameLayer convertToWorldSpace:_origin];

CGPoint _nodePos = ccpSub(wOrigin, wPlayer);

[gameLayer setPosition:_nodePos];

}


This method should be executed each timestep to keep your layer centered.
Happy gamedeving :)

No comments:

Post a Comment