100 Days of Code - Day 7

Written by Josh Fabean

07. September 2016

I just finished day 7! Where did the other days go you say… well I did them but only on github without blogs. I’ve been busy :) This in 7-10 hours is actually becoming a real thing. At this point here’s some key features I have done:

  • Fly around the screen with turning and when you hit the edge of the screen you go to the other side of the screen
  • You can shoot lasers by pressing the space key
  • Randomly generated asteroids appear and fly across the screen
  • You can shoot the asteroids and they disappear and you get a point
  • You can get hit by an asteroid and they disappear and you lose a point
  • I just today fixed my words which weren’t showing up. Turns out they were alwasy there… just black instead of white.

Most of the things in that list don’t work great but they work, I’m honestly impressed with how little I’ve worked on this.

So today my commit is first my updated log file and the actual code I wrote.

Here’s my current hit detection code, which I believe would work if things weren’t rotated on the screen.

// calculate if you hit an asteroid
let calcLaserHits = () => {
  // for each laser current on screen
  for (let i = 0; i < player.ship.lasers.active.length; i++) {
    let laser = player.ship.lasers.active[i];
    // for each asteroid currently on the screen
    for (let a = 0; a < asteroids.length; a++) {
      if (laser.x >= asteroids[a].x && // if your x is greater than the asteroid
          laser.x <= (asteroids[a].x + asteroids[a].width) && // and less that the asteroids x+the width you should be between it on the x axis
          laser.y <= asteroids[a].y && // if your y is less (above) the asteroid I actually feel like this is wrong...
          laser.y >= (asteroids[a].y - asteroids[a].height) // and you are greaterthan it's y and up.
         ) {
        // you should be between this asteroid
        console.log('you hit an asteroid!');
        asteroids.splice(a, 1);
        player.score++;
      }
    }
  }
}

Now that I’ve commented that if I’m confused by this and I think my if is wrong and that’s why the hit detection is bad. Maybe looking that over again and fixing that will make things better. Hopefully that’s the case and I don’t have to do some crazy math based on rectangles being rotated.

Here is my code in CodePen as it currently stands, you can use the arrow keys and space to play with it. Like I said above collision detection could use some help

See the Pen 100 Days of Code day 7 by Josh Fabean (@fabean) on CodePen.

:wq