space invaders clone
This is the first project I worked on after starting to study at the Amsterdam University of Applied Sciences. This was a solo project for which I worked with javascript and p5.js. project.
For this project we had learned some basics of how to make video games. One of the things we learned was how to make rectangle and circle colliders. However when I started using sprites that didn’t fit either of these shapes the game started to feel unfair because the hit triggers and the visuals didn’t match. So I had to come up with a solution.
The first step I took was thinking about what exactly had to happen. I decided that, since I had multiple sprites, the code should work for any shape. The idea I had was to give the corners of the object and calculate the lines on the outside of the object. Using these lines I could calculate if any of the lines of object A overlapped with the lines of object B. I drew an example of what had to happen to visualize the idea which can be seen below.
In this image you can see object D (bottom left) and object C (top right). The red cross indicates a collision and the green dotted line and cross indicate that that they should only collide if the collision point is between the two corners of the line that is checked for collision.
Step 1 calculate lines:
To calculate the lines between the corners we have to calculate the difference in x and y positions between the first corner and the second corner. We then divide the y difference by the x differencec to get the slope. We can transform the formula y = ax + b to b = y – (ax) to get the offset.
Step 2 calculate collision points:
To calculate the collision points, we have to compare every combination of 2 lines of the 2 given objects A and B. We do this by calculating (offset A – offset B) / -(slope A – slope B). We make one extra check to make sure a slope isn’t equal to 0 or infinity, because we have to give them a different value.
Step 3 check for collision:
The last step is seeing if the points calculated in step 2 are within the given corners. We have to use Math.min and Math.max to make sure we get the largest numbers in the same variable for every combination of corners so we can decide whether the collision point should be greater than or smaller than the given corner.