Game Development Reference
In-Depth Information
@Override
public void update( float deltaTime) {
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
game.getInput().getKeyEvents();
int len = touchEvents.size();
for ( int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
touchPos.x = (event.x / ( float ) glGraphics.getWidth())
* FRUSTUM_WIDTH;
touchPos.y = (1 - event.y / ( float ) glGraphics.getHeight())
* FRUSTUM_HEIGHT;
cannonAngle = touchPos.sub(cannonPos).angle();
if (event.type == TouchEvent. TOUCH_UP ) {
float radians = cannonAngle * Vector2. TO_RADIANS ;
float ballSpeed = touchPos.len();
ballPos.set(cannonPos);
ballVelocity.x = FloatMath. cos (radians) * ballSpeed;
ballVelocity.y = FloatMath. sin (radians) * ballSpeed;
}
}
ballVelocity.add(gravity.x * deltaTime, gravity.y * deltaTime);
ballPos.add(ballVelocity.x * deltaTime, ballVelocity.y * deltaTime);
}
The update() method has changed only slightly. The calculation of the touch point in world
coordinates and the angle of the cannon are still the same. The first addition is the if statement
inside the event-processing loop. In case we get a touch-up event, we prepare the cannonball
to be shot. We transform the cannon's aiming angle to radians, as we'll use FastMath.cos()
and FastMath.sin() later on. Next, we calculate the distance between the cannon and the
touch point. This will be the speed of the cannonball. We set the ball's position to the cannon's
position. Finally, we calculate the initial velocity of the cannonball. We use sine and cosine, as
discussed in the previous section, to construct a direction vector from the cannon's angle. We
multiply this direction vector by the cannonball's speed to arrive at the final cannonball velocity.
This is interesting, as the cannonball will have this velocity from the start. In the real world,
the cannonball would, of course, accelerate from 0 m/s to whatever it could reach given air
resistance, gravity, and the force applied to it by the cannon. We can cheat here, though, as that
acceleration would happen in a very tiny time window (a couple hundred milliseconds). The last
thing we do in the update() method is update the velocity of the cannonball and, based on that,
adjust its position.
@Override
public void present( float deltaTime) {
GL10 gl = glGraphics.getGL();
gl.glViewport(0, 0, glGraphics.getWidth(), glGraphics.getHeight());
gl.glClear(GL10. GL_COLOR_BUFFER_BIT );
gl.glMatrixMode(GL10. GL_PROJECTION );
Search WWH ::




Custom Search