Thursday, April 19, 2012

More Collision Detection

Collision detection for the Square rooms went well and the code work just as posted (some values were reversed). The next challenge was to apply collision detection to the boss chamber which is an octagon shape. The four side that were like the square rooms were easy to do, but the diagonal sides were tough at first. I could have used a QPen tool to detect collision, but I needed to anticipate if a collision would happen. This required me to pull out my algebra knowledge (which was almost lost to time).

My first instinct was to get the point of the hero and project that on the diagonal line which would be perpendicular to each other. This works perfectly well as the equation for a perpendicular line is y - y1 = -1/m (x - x1). Just find intersection and if the distance to intersection was shorter than total distance traveled by the hero, then you would have a collision. This seemed simple enough on paper, but implementing the code was hard and really frustrating. The final result semi worked and I had to work to fine tune it. I then talked to a friend who has his BS in Math. He suggested a different approach using his knowledge from Foundations of Analysis. Starting from the well known formula y = mx + b and using (a,b) (c,d) for points he was able to find the formula that would help me. I forgot his exact steps, but he was able to prove that slope = (d-b)/(c-a) and got the formula y = slope * x + b - slope * a for when the hero was moving in the y axis up. Simply rearrange the formula for x (x = (y - b + slope * a)/slope)) and you got when the hero would cross in the x - axis. To check diagonally, you would then check the y axis, then the x axis. Then by tweaking a,b,c, and d you could use it on any diagonal line. This proves that a good understanding in Math is extremely useful for programming challenges and it is always good to have a math major around.

All the collision detection is done in my level and I am working on basic enemy AI and the player being able to kill them.

No comments:

Post a Comment