Squashing a lot of bugs this week, nothing new to show off. Instead of showing something new, I am going to explain how a part of the game works, namely the laser hit detection.
Most of the hit detection in the game are basic hit boxes that detect when objects overlap. This method is quick and efficient for small or basic objects, however for large or oddly shaped objects it can be inaccurate. For example, both the laser power up and the gunship's main cannon fire lasers that have an area of effect that is long but thin. Using square hit boxes for these is slow and can create many areas where the detection is off. I had to develop a better method of detection to make these power ups work.
|
the laser powerup |
|
the gunship's main cannon |
I decided to use as simple approach as possible. Since these objects are just straight lines, I used the tried and true y=mx+b formula from early algebra.
|
collision detection formula explanation (click to view) |
The idea behind this is that if a formula for the laser line could be found, it could be used to find the position the ship would need to be if it were hit. If the player is within a tolerance lying on this line, a collision has occurred and the player will be hurt.
The formula is created by creating an axis centered around the point of production of the laser. This makes the "y intercept" of the line zero so it is much more manageable. The slope (m) is just a conversion of the angle the laser it at using trig functions. This leaves just the y and x variables in the equation, which we can use as a function to detect where the hit position is.
The player's x position is put into the formula at the x variable and this outputs the y position on the line where it would be it were hit by the laser. This is just compared to the actual y position with a tolerance to see if the actual ship position is within the laser's line. If it is, a hit signal is sent, otherwise it doesn't need to do anything since it missed.
This will detect a hit on both sides of the projection point, which works great for the laser powerup since it is projected in both directions but for the gunship laser it can trigger false positives. This was altered by determining which direction the gunship is facing, and then ignoring the x positions in the opposite direction. This prevents targets behind the gunship from being hit even if the laser isn't facing it.
This method detects hits for attacks based on lines and works pretty efficiently. It can be optimized further to be quicker and more accurate, but it does its job well.