Game Development Reference
In-Depth Information
int len = touchEvents.size();
for ( int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
touchPos.x = (event.x / ( float ) glGraphics.getWidth()) * WORLD_WIDTH;
touchPos.y = (1 - event.y / ( float ) glGraphics.getHeight()) * WORLD_HEIGHT;
cannon.angle = touchPos.sub(cannon.position).angle();
if (event.type == TouchEvent. TOUCH_UP ) {
float radians = cannon.angle * Vector2. TO_RADIANS ;
float ballSpeed = touchPos.len() * 2;
ball.position.set(cannon.position);
ball.velocity.x = FloatMath. cos (radians) * ballSpeed;
ball.velocity.y = FloatMath. sin (radians) * ballSpeed;
ball.bounds.lowerLeft.set(ball.position.x - 0.1f, ball.position.y - 0.1f);
}
}
ball.velocity.add(gravity.x * deltaTime, gravity.y * deltaTime);
ball.position.add(ball.velocity.x * deltaTime, ball.velocity.y * deltaTime);
ball.bounds.lowerLeft.add(ball.velocity.x * deltaTime, ball.velocity.y * deltaTime);
List<GameObject> colliders = grid.getPotentialColliders(ball);
len = colliders.size();
for ( int i = 0; i < len; i++) {
GameObject collider = colliders.get(i);
if (OverlapTester. overlapRectangles (ball.bounds, collider.bounds)) {
grid.removeObject(collider);
targets.remove(collider);
}
}
}
As always, first we fetch the touch and key events, and only iterate over the touch events. The
handling of touch events is nearly the same as in the CannonGravityTest . The only difference is
that we use the Cannon object instead of the vectors we had in the old example, and we reset the
ball's bounding rectangle when the cannon is ready to shoot after a touch-up event.
The next change is in how we update the ball. Instead of straight vectors, we use the members
of the DynamicGameObject that we instantiated for the ball. We neglect the DynamicGameObject.
acceleration member, and instead add gravity to the ball's velocity. We multiply the ball's speed
by 2, so that the cannonball flies a little faster. The interesting thing is that we update not only
the ball's position, but also the position of the lower-left corner of the bounding rectangle. This
is crucial, as otherwise our ball will move but its bounding rectangle won't. Is there a reason
why we don't simply use the ball's bounding rectangle to store the ball's position? We might
want to have multiple bounding shapes attached to an object. Which bounding shape would
then hold the actual position of the object? Separating these two things is thus beneficial,
and it introduces only a slight computational overhead. We could, of course, optimize this by
multiplying the velocity with the delta time only once. The overhead would then boil down to two
further additions—a small price to pay for the flexibility we gain.
Search WWH ::




Custom Search