penguinsource
penguinsource

Reputation: 1200

Cocos2d coordinate system

in cocos2d, the coordinate system is pretty straightforward.. bottom left is (0,0). whenever i set the position of anything it's fine.

lets say a layer is TouchEnabled.

when im setting the position of my sprite, it's fine..

[crab setPosition:ccp(20, 50)];

but if i get the x and y coordinate of a touch (and assume i clicked on the sprite..):

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Touches began!");
    NSArray *touchArray = [touches allObjects];
    UITouch *one = [touchArray objectAtIndex:0];
    pointOne = [one locationInView:[one view]];
    CCLOG(@"points are: %f and %f", pointOne.x, pointOne.y );
}

the y coordinate is the opposite of what cocos2d's coordinate system suggests as the y increases from top to bottom !

so im assuming the coordinate system of the view is different than mac's coord system.. which is quite counter intuitive.. is that correct?

thanks !

Upvotes: 5

Views: 3769

Answers (5)

Ben Trengrove
Ben Trengrove

Reputation: 8769

OpenGL uses a (0, 0) of bottom left while iOS and therefore UIKit which handles the touches use top left as (0, 0). It is easy to convert your point over, you just have to remember to do it.

The correct method on cocos2d 2.0 is

CGPoint uiKitPoint = [touch locationInView:touch.view];
CGPoint cocos2dPoint = [[CCDirector sharedDirector] convertToGL:uiKitPoint];

Upvotes: 4

Ilker Baltaci
Ilker Baltaci

Reputation: 11787

This cocos2d tutorial might help you

http://www.gamefromscratch.com/post/2012/06/08/Cocos2D-HTML-Tutorial-3All-about-sprites-and-positioning.aspx

But generally speaking in cocos2d point (0,0) is the left corner of the screen

Upvotes: 1

lukaswelte
lukaswelte

Reputation: 3001

The Touches come from UIKit which top left is (0,0) so you need to convert it to the coordinate system of cocos2d before handling with this data.

There is

[[CCDirector sharedDirector] convertToGL];

For UIkit -> cocos2d

Upvotes: 0

robc
robc

Reputation: 181

Typically, for most graphics related applications, there is a tendency to place (0, 0) at the lower-left (and this is the case with the Mac) - where as on iOS, it's positioned at the top-left as you've noticed.

When you're handling input with Cocos, you can quickly convert it over by using the convertTouchToNodeSpace method (at least with 1.x - I've not played with 2.0 enough - but I believe it's convertToNodeSpace there from a quick documentation check). This will then do the necessary transformations to give you the right coordinate.

(NB: I need to dig up some of my other code to double check - but I can't remember off the top of my head whether this counts of camera offsets as well - I'll edit when I can get to my demo code & confirm.)

Upvotes: 0

Cocos2D already can handle this for you. The CCDirector has some methods for this. Please, take a look at this older post.

Upvotes: 0

Related Questions