PatrickC - Get in touch through the cocos2d forums.
Tested on 0.8.1 - Should work on 0.8.x
Camera changes in >=0.9 change a small fix, you'll find that commented in the code
When translating and zooming in/out with a camera (changing Z value), the coordinates returned by the standard conversions are wrong. The code proposed takes into account translation and Z value (zoom), but not rotation. Also, this code is adapted for Landscape orientation, although changing it to suite Portrait should be a very easy matter.
First, let's create our custom method, that will convert the coordinate
-(CGPoint)convertCoordToLayer:(CGPoint)point {
float centerX, centerY, centerZ;
float eyeX, eyeY, eyeZ;
[self.camera centerX:¢erX centerY:¢erY centerZ:¢erZ];
[self.camera eyeX:&eyeX eyeY:&eyeY eyeZ:&eyeZ];
CGSize screenSize = [[Director sharedDirector] winSize];
float origCameraX = ( screenSize.width / 2.0f );
float origCameraY = ( screenSize.height / 2.0f );
float origCameraZ = ( screenSize.width / 1.1566f );
point.x = ((centerX - origCameraY) + point.x);
point.y = ((centerY - origCameraX) + point.y);
//for cocos2d 0.8.2 and below, there's a bug with landscape orientation camera, so we need to offset by 80 pixels
//on X and Y. If using cocos2d 0.9 or greater, this fix should no longer be necessary, set fixValue to 0. (testing required)
int fixValue = 80;
point.x=point.x-((point.x-(centerX+fixValue))*(1-(eyeZ/origCameraZ)));
point.y=point.y-((point.y-(centerY-fixValue))*(1-(eyeZ/origCameraZ)));
return point;
}
We can then call our newly created method whenever necessary. You will first want to convert the coordinate to landscape by calling cocos2d's convertCoordinate method
Example in ccTouchesBegan:
- (BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[touches allObjects] objectAtIndex:0];
CGPoint location = [touch locationInView: [touch view]];
location = [[Director sharedDirector] convertCoordinate: location];
location = [self convertCoordToLayer:location];
....
}
Needs to be tested with 0.9 (removing the 80 pixel offset)
Could be better implemented to automatically adapt to landscape/portrait, be more readable, etc etc…