Game Development Reference
In-Depth Information
worldX = (touchX / Graphics.getWidth()) * viewFrustmWidth
worldY = (1 - touchY / Graphics.getHeight()) * viewFrustumHeight
We normalize the touch coordinates to the range (0,1) by dividing them by the screen resolution.
In the case of the y coordinate, we subtract the normalized y coordinate of the touch event from
1 to flip the y axis. All that's left is scaling the x and y coordinates by the view frustum's width
and height—in our case, that's 4.8 and 3.2. From
worldX
and
worldY
, we can then construct a
Vector2
that stores the position of the touch point in your world's coordinates.
The last thing we need to do is calculate the angle with which to rotate the canon. Take a look at
Figure
8-5
, which shows our cannon and a touch point in world coordinates.
Figure 8-5.
Our cannon in its default state, pointing to the right (angle = 0°), a touch point, and the angle by which we need
to rotate the cannon. The rectangle is the area of the world that our view frustum will show on the screen: (0,0) to (4.8,3.2)
All we need to do is create a distance vector from the cannon's center at (2.4,0.5) to the touch
point (and remember, we have to subtract the cannon's center from the touch point, not the
other way around). Once we have that distance vector, we can calculate the angle with the
Vector2.angle()
method. This angle can then be used to rotate your model via
glRotatef()
.
Let's code that. Listing 8-2 shows the relevant portion of your
CannonScreen
, part of the
CannonTest
class, with comments added were appropriate.
Listing 8-2. Excerpt from CannonTest.java; Touching the Screen Will Rotate the Cannon
class
CannonScreen
extends
Screen {
float
FRUSTUM_WIDTH = 4.8f;
float
FRUSTUM_HEIGHT = 3.2f;
GLGraphics glGraphics;
Vertices vertices;
Vector2 cannonPos =
new
Vector2(2.4f, 0.5f);
float
cannonAngle = 0;
Vector2 touchPos =
new
Vector2();
We start off with two constants that define your frustum's width and height, as discussed earlier.
Next, we include a
GLGraphics
instance and a
Vertices
instance. We store the cannon's position
in a
Vector2
and its angle in a float. Finally, we have another
Vector2
, which we can use to
calculate the angle between a vector from the origin to the touch point and the x axis.