Skip to content
Advertisement

How can I change the angle of a vector when hitting an obstacle

So, my issue concerns vectors, I don’t know where I’m going with that case. I’m building a pandemic simulation (using Javascript and the library p5.js), and I’m trying to add a lockdown feature.

Here is an image to make everything clearer:

Pandemic simulation

Essentially, at the moment, when two molecules collide, their velocity vector change appropriately by switching their former velocity.

JavaScript

My issue arises when I want to change a vector’s angle when a molecule hits another fixed molecule. Unlike the code above, the fixed molecule has to stay still. Thus, I assume that I can’t set this.velocity.x (or y) to be simply reversed.

The bounce method gets two parameters: _molecule (or ball B, the one which ball A collides with) and the distance, calculated as such:

JavaScript

I assume that I have to use Sine and Cosine, but I’m not really sure about it.

Advertisement

Answer

I’ve created a tutorial on OpenProcessing that I think should help you understand the vector math for dealing with collisions between moving and stationary circular objects. In short, one circular object colliding with another can be generalized as the collision between that circle and the line that is tangent to the other circle and perpendicular to the line from the center of one circle and the other.

Here is the relevant code sample from page 4 of the tutorial:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement