Detecting Collisions

This game won’t be any fun if there’s no element of danger. Open up collisions.ts and take a look around. I’ve filled in the math stuff that isn’t as relevant to the Rx core. There’s a checkCollision function that operates much like the other updates you’ve seen. This one’s filled out, since it’s more of the same that you’ve already written. One thing that sticks out is a tracker for how many frames have elapsed since an explosion happened.

 gameState.explosions.forEach(e =>
  e.framesSince++;
 );

We need to track this value since the explosion is animated. Canvas doesn’t allow traditional gifs, so we need to manually animate. Let’s skip ahead to the render function and see how that plays out:

 export​ ​function​ renderExplosions (gameState: GameState) {
  gameState.explosions.forEach(e => {
 if​ (e.framesSince > config.explosion.frames *
  config.explosion.gameFramesPer) { ​return​; }
  ctx.drawImage(
  explosionImg,
  Math.floor(e.framesSince / config.explosion.gameFramesPer) *
  config.explosion.width,
  0,
  config.explosion.width,
  config.explosion.height,
  e.x,
  e.y,
  config[e.type].width,
  config[e.type].height
  );
  });
 }

This function iterates over all of the explosions attached to the game state, skipping over the ones that completed their animation. If an explosion is still animating, we draw an image (just like the player/pirate ships), but instead of a static image, we draw a single frame from a sprite sheet. This sprite sheet is a single image that contains every frame of the animation. Instead of drawing the entire image, we draw only a subsection.

images/explosion.png

Add checkCollision and renderExplosions to the Rx backbone in index.ts. At this point, you have a colliding function, a type definition for explosion, and two sets of lasers to check. Try to figure out what you need to write inside checkCollision to get the game to update. Hint: don’t forget to set alive to false. If you get stuck, don’t worry; take a peek at the answer in the rxfighter-finished folder.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.138.178