Dieses Dokuwiki verwendet ein von Anymorphic Webdesign erstelltes Thema.

Getting correct touch coordinates when moving/scaling a camera (Landscape)

Author

PatrickC - Get in touch through the cocos2d forums.

http://www.cleverhamstergames.com

Versions

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

Problem

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.

Solution

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:&centerX centerY:&centerY centerZ:&centerZ];
	[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];
        ....
}

Discussion

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…

See also

cookbook/touchcoordcamera.txt · Last modified: 2010/02/14 14:58 by patrickc
Trace: animation instructions touchcoordcamera
Dieses Dokuwiki verwendet ein von Anymorphic Webdesign erstelltes Thema.
CC Attribution-Noncommercial-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0