Search code examples
c++cocos2d-x

CCPoint to float conversion


What I'm trying to do : Have the coordinates of where i touch the screen put into 2 floats, x and y.

What I understand is that to get the coordinate of where I'm touching I should be using getLocation(). So I wrote a small piece of code :

CCTouch *pTouch;
CCPoint *xy = pTouch->getLocation();

How I understand it (Which could quite possibly be wrong), this should have the variable xy set to equal the opengl coordinates of where the screen was touched. IF this is the case, how would I convert this CCPoint variable into a float or two(x and y float values)?


Solution

  • Here's what you can do. In the init() function of your scene class add the call

    setTouchEnabled( true );
    

    to tell cocos2d-x to tell you about touch events by calling ccTouchBegan, ccTouchMoved, ccTouchCancelled and ccTouchEnded on the scene as appropriate. Now, when these functions are called you get passed a

    cocos2d::CCTouch *touch
    

    which you can use to get the touch coordinates. What I do in my game is

    CCPoint p = touch->getLocationInView();
    p = CCDirector::sharedDirector()->convertToGL(p);
    

    and p will contain the coordinates of the touch. You can get the float values of the x and y coordinates of the touch by doing

    float x = p.x;
    float y = p.y;
    

    Hope that helps. :)