Game Development Community

Converting GUI coordinates to World coordinates

by Shaz · in Torque Game Builder · 08/10/2008 (2:30 am) · 2 replies

I have been toying with placing scene objects using GUI coordinates, and rather than struggle with guessing and reguessing placement, I've come up with the following small function that seems to do the job nicely (I'll be crushed if someone says there's already a way to do this!)

// convert GUI coordinates to world coordinates
function GuiToWorld(%x, %y)
{
   %xscale = getWord(sceneWindow2D.getSceneGraph().cameraSize, 0) / getWord($Game::Resolution, 0);
   %yscale = getWord(sceneWindow2D.getSceneGraph().cameraSize, 1) / getWord($Game::Resolution, 1);
   
   %newx = (%x - (getWord($Game::Resolution, 0) / 2)) * %xscale;
   %newy = (%y - (getWord($Game::Resolution, 1) / 2)) * %yscale;
   
   return %newx SPC %newy;
}

The following calls and output seems to suggest all is ok:

echo("GUI: 0 0 becomes World: " @ GuiToWorld(0, 0));
   echo("GUI: 400 300 becomes World: " @ GuiToWorld(400, 300));
   echo("GUI: 800 600 becomes World: " @ GuiToWorld(800, 600));

...

GUI: 0 0 becomes World: -50 -37.5
GUI: 400 300 becomes World: 0 0
GUI: 800 600 becomes World: 50 37.5


This has a few issues if you try to use it with scene objects (which are placed according to their center, while GUI objects are placed according to the top left corner). The easy solution is to add an offset to the x and y coordinates of the width and height / 2. I did have to do a little more tweaking to get them in just the right spot. And the size has to be scaled accordingly (camera view = 1/8 resolution -> image sizes must be scaled to 1/8 as well).

I do have an unresolved issue where behaviours added to t2dStaticSprites placed using this method don't always trigger - I'm getting about a 50% success rate at the moment. I suspect the problem is related to the behaviour still looking at the original size of the image. Haven't reached my wits end on that one yet...

Would appreciate any thoughts/comments/pointing out of bugs with the above code as I'm still pretty green.

#1
08/10/2008 (2:36 am)
T2dSceneWindows already contain this method: t2dSceneWindow::getWorldPoint(x, y)
#2
08/10/2008 (2:49 am)
Thanks - I'll take a look. Wonder if it'll sort out my other problems...