Thursday, June 7, 2018

Ball vs 45-degree slope collision detection


I have a simple game in which the player moves a ball around. The ball bounces off of walls. Right now I have square walls(■) implemented: I use simple bounding-box collisions to check if the player will move into a wall when updating its x or y speed and if so, I multiply that speed with -1 to make them bounce.


However, I also want to implement triangular pieces(◢◣◤◥). To bounce back I believe one can simply use:



   newxspeed = -1*yspeed;
newyspeed = -1*xspeed;

However, what I am having trouble with is the collision detection: When does the player hit the diagonal?



Answer



First of all in order to calculate the collision detection between a sphere(circle in 2D) and a line you need to calculate the perpendicular vector between the moving ball's center and the line, in order to calculate this distance you need to do the following:


enter image description here


So in order to calculate d in the above figure we need to do some steps.



  1. Assume your line is using the parametric equation P(t) = S + t V note that V is the line direction can be obtained by subtracting (P2 - P1).


  2. From Pythagoras:



d^2 = len(Q - S)^2 - len( proj(Q - S ) )^2



Then you expand the equation to get the following, it seems a bit complicated but it's actually not.



d = sqrt( len(Q - S)^2 - len( (Q - S) dot V )^2 / V^2 )



Where Q is the circle's center and S is any point on the line. Once the distance is less than the circle/sphere radius you need to trigger collision response which is explained in the next point.



It's incorrect to always flip the x or y component to bounce the ball, what you need to do is to reflect the velocity vector, in order to do so you need to calculate the Normal vector of the surface and use that normal for calculating the reflection vector using the following equation



R = 2 * (V dot N)* N - V



where R is the reflection vector, N is the normal of the surface and V is the Velocity vector.


In case of 45 deg your surface normal will be N = (1,1,0) with varying sign depending on which direction the normal faces (position or negative).


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...