This project is read-only.

Mouse coordinate conversion

Topics: Platform UI
Nov 26, 2013 at 7:28 PM
Hi there. I'm currently writing some test apps using the WindowsGL template for Cocos2D-XNA and I'm having some trouble positioning sprites using the mouse... I'm trying to move a sprite to a location I click in the window. It looks like I need to translate the mouse position into the Cocos2D-XNA coordinate system but I'm not sure of the proper way to do so. What's the best way to accomplish this? Thanks.
Nov 26, 2013 at 7:57 PM
Well, I did get it converted to position the sprite correctly in the game window using the following code:
position.X = (position.X * CCDirector.SharedDirector.WinSize.Width) / 800;
position.Y = CCDirector.SharedDirector.WinSize.Height - ((position.Y * CCDirector.SharedDirector.WinSize.Height) / 480);
In more general terms:
newPositionX = (curPositionX * newScaleX) / curScaleX;
newPositionY = (curPositionY * newScaleY) / curScaleY;
What I don't like is the hack of the hard-coded values I have in there for the conversion (800 & 480)... those I got by checking the range of the raw mouse coordinates inside the client rectangle of the game window. If there's a better way to do this, any suggestions would be greatly appreciated. :D Thanks.
Nov 26, 2013 at 8:32 PM
After further exploration, it looks like I can get rid of my hard-coded values by using the Viewport object off of the graphics device. So I have the following new code:
            // Convert the mouse position into Cocos2D-XNA position
            position.X = (position.X * CCDirector.SharedDirector.WinSize.Width) / 
            position.Y = CCDirector.SharedDirector.WinSize.Height - ((position.Y * CCDirector.SharedDirector.WinSize.Height) /
So this seems to work fine. Still, if there's a better way to do this, I'd appreciate any suggestions. Thanks.
Dec 7, 2013 at 7:00 PM

when you click, you can get the location or the location in the view. The location is the GL location, whereupon you would transform the location to your node coordinate space.

There are numerous transform helpers in CCNode to transform from local node, to world, and then to other node spaces. I suggest you use those transforms instead of writing your own. We have OpenGL games too and they all work fine for touch location handling without any special math calculations as you have done.