Game Development Reference
In-Depth Information
direction the cannon is pointing. Also, we set the speed simply by multiplying the velocity by the
distance between the touch point and the cannon. The closer the touch point to the cannon,
the more slowly the cannonball will fly.
Sounds easy enough, so now we can try implementing it. Copy over the code from the
CannonTest.java
file to a new file, called
CannonGravityTest.java
. Rename the classes
contained in that file to
CannonGravityTest
and
CannonGravityScreen
. Listing 8-3 shows the
CannonGravityScreen
class, with some comments added for clarity.
Listing 8-3. Excerpt from CannonGravityTest
class
CannonGravityScreen
extends
Screen {
float
FRUSTUM_WIDTH = 9.6f;
float
FRUSTUM_HEIGHT = 6.4f;
GLGraphics glGraphics;
Vertices cannonVertices;
Vertices ballVertices;
Vector2 cannonPos =
new
Vector2();
float
cannonAngle = 0;
Vector2 touchPos =
new
Vector2();
Vector2 ballPos =
new
Vector2(0,0);
Vector2 ballVelocity =
new
Vector2(0,0);
Vector2 gravity =
new
Vector2(0,-10);
Not a lot has changed. We simply doubled the size of the view frustum, and reflected that by
setting
FRUSTUM_WIDTH
and
FRUSTUM_HEIGHT
to 9.6 and 6.2, respectively. This means that we
can see a rectangle of 9.2×6.2 m of the world. Since we also want to draw the cannonball,
we add another
Vertices
instance, called
ballVertices
, which will hold the four vertices and
six indices of the rectangle of the cannonball. The new members
ballPos
and
ballVelocity
store the position and velocity of the cannonball, and the member
gravity
is the gravitational
acceleration, which will stay at a constant (0,-10) m/s
2
over the lifetime of our program.
public
CannonGravityScreen(Game game) {
super
(game);
glGraphics = ((GLGame) game).getGLGraphics();
cannonVertices =
new
Vertices(glGraphics, 3, 0,
false
,
false
);
cannonVertices.setVertices(
new float
[] { -0.5f, -0.5f,
0.5f, 0.0f,
-0.5f, 0.5f }, 0, 6);
ballVertices =
new
Vertices(glGraphics, 4, 6,
false
,
false
);
ballVertices.setVertices(
new float
[] { -0.1f, -0.1f,
0.1f, -0.1f,
0.1f, 0.1f,
-0.1f, 0.1f }, 0, 8);
ballVertices.setIndices(
new short
[] {0, 1, 2, 2, 3, 0}, 0, 6);
}
In the constructor, we simply create the additional
Vertices
instance for the rectangle of the
cannonball. We define it in model space with the vertices (-0.1,-0.1), (0.1,-0.1), (0.1,0.1), and
(-0.1,0.1). We use indexed drawing, and thus specify six vertices in this case.