Hi,
I’m attempting to create a collision detection algorthm however it fails even though it seems logical to me:
void Collision_Detector()
{
for (int i = 0; i < particles.size(); i++) // Get the individual particle in the vector (P1)
{
for (int c = 0; c < particles.size(); c++) // Use the all other particles in vector and check if they collide with the particle (P1)
{
if (c != i) // EXCEPT from itself
{
if (particles[c].x == particles[i].x) // Check if particle (P1) and the other particles are in the same X axis direction
{
float distance = particles[i].y - particles[c].y; // IF SO calculate vertical distance from each other.
if (distance < 0.50) // If the distance is greater than 0.50 show messagebox
{
MessageBoxW(0,"Collision Detected","Great!",MB_OK);
}
}
}
}
}
}
The above algorithm makes perfect sense yet it fails to work and it shows message box everytime I create particle in the same X axis location even when the both Y axis are like 200.00 distance away. Why is this can someone help?
Capt.Yoda
Try:
float distance = abs (particles[i].y - particles[c].y);
Claude
Hi,
It works but when I try find the hyptoenuse distance it fails is there anything wrong heere:
void Collision_Detector()
{
for (int i = 0; i < particles.size(); i++) // Get the individual particle in the vector (P1)
{
for (int c = 0; c < particles.size(); c++) // Use the all other particles in vector and check if they collide with the particle (P1)
{
if (c != i) // EXCEPT from itself
{
if (particles[c].x == particles[i].x) // Check if particle (P1) and the other particles are in the same X axis direction
{
float distance_y = abs(particles[i].y - particles[c].y); // Find distance in Y Axis
float distance_x = abs(particles[i].x - particles[c].x); // Find distance in X Axis
float hyptenuse_y = distance_y * distance_y + distance_x * distance_x; // FIND HYPOTENUSE
float finalDistance = sqrt(hyptenuse_y);
if (finalDistance < 1.0) // IF HYPOTENUSE IS GREATER THAN 1 THEY COLLIDED
{
MessageBox(0, 0, 0, 0);
}
}
}
}
}
}
What am I doing wrong, is there a better way to find the distance between them?
Capt.Yoda
Try this:
Remove this test:
if (particles[c].x == particles[i].x)
With it you need the x coordinates to be equal to have a collision.
You should use the formula: c = squareroot[ (xa-xb)² + (ya-yb)² ]
http://www.mathsisfun.com/algebra/distance-2-points.html
Same thing.Faster.No abs.
Hope it helps.
Claude
Hi,
That solved the problem, now anyway I still has to use abs but its not really an concern. Thanks though.