2D vertical angular collisions

73 views Asked by At

Currently I am working on a 2D particle simulator. I have each particle moving on a unique angle. I found a basic formula to change x and y velocity, but I currently have a set velocity that moves according to the angle.

particles[a][3] += particles[a][1] * cos(radians(particles[a][5]));//move X
particles[a][4] += particles[a][1] * sin(radians(particles[a][5]));//move Y

I have a basic collision for collisions on walls, but can't find the best way to sort the collisions out. Currently I just multiply the rotation by -1, but that only works on the top and bottom. Note: The particle will always move after running the collision (its not getting stuck in the collision boxes and bugging out).

if(particles[a][3] < 0 || particles[a][3] > windowWidth/2 || particles[a][4] < 0 || particles[a][4] > windowHeight/2) {
    /*windowWidth and windowHeight are divided by 2 to find the canvas size. In the setup() I have the canvas set to that value).*/
    particles[a][5] *= -1;
}

Array values:

particles[a][1] = speed
particles[a][3] = x position
particles[a][4] = y position
particles[a][5] = rotation

My question is what is the best way to run these collision tests. I understand that collisions bounce at 90 degrees, but I'd like to use as few if statements as possible (simpler the better) instead of a tedious bunch.

Merry Christmas, and thanks in advance!


Figured it out! Final code:

if(particles[a][4] < 0 || particles[a][4] > windowHeight/2) {
    particles[a][5] *= -1;
} else if(particles[a][3] < 0 || particles[a][3] > windowWidth/2) {
    particles[a][5] = 180 - particles[a][5];
}
1

There are 1 answers

2
Kevin Workman On BEST ANSWER

Try googling "javascript reflect angle" and you'll find formulas for reflecting around both the X and Y axis. You do one when you collide with the top or bottom, and you do the other when you collide with the left or right.

Also, you probably shouldn't be using an array to hold your data. Create a class that holds your values, and then create instances of that class. Using magic array indexes is a recipe for headaches.

If you still can't get it working, then please post an MCVE and we'll go from there. Good luck.