Paul
Paul

Reputation: 6176

How to calculate the touch location with convertToWorldSpace?

i would like to convert the touch location as a world coordinate in my tile game. With this code, i clicked on the right of the screen (so that my character walks in the tiled game, and the background goes slowly to the left) :

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    for( UITouch *touch in touches ) {
        CGPoint location = [touch locationInView: [touch view]];

        location = [[CCDirector sharedDirector] convertToGL: location];
        CGPoint test = [self convertToWorldSpace:location];

        CCLOG(@"test : %.2g", test.x);

The test log gives me :

50, 72, 1e+02, 2.6e+02, 4.2e+02, (and then goes down) 3.2e+02, 9.5, -1.9e+02, etc.

Does anyone know why? I would like to calculate the "real" coordinate of the touch, so that i know when the character has to keep going (click on the right of its actual position) or if he has to turn and go backwards. (click on the left of its actual position)

Thanks for your help

Upvotes: 0

Views: 386

Answers (2)

Morion
Morion

Reputation: 10860

All that you are doing with cocos2d, you do in single OpenGL view. So, if you handle touches by your scene or layer with the size of scene, it is enough to call these lines

    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL: location];

to get touch position relatieve to your screen. convertToWorldSpace just translates local node coordinates to world coordinates

Upvotes: 1

Alexis King
Alexis King

Reputation: 43902

Those numbers printed look fine, but you're using the %g format specifier, which according to Apple's documentation on the subject, does this:

64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.

Unless that's what you want, you should probably use %f instead, which won't produce any numbers in scientific notation.

Upvotes: 1

Related Questions