Skip to content
Advertisement

Elastic collision simulation

I’m trying to simulate elastic collision using the One-dimensional Newtonian equation (https://en.wikipedia.org/wiki/Elastic_collision) with pygame. The thing is that even if I transcribed the solved equation to change the velocity of the 2 bodies, it is not working (or probably there is something wrong with the code). Here it is the code:

JavaScript

Since the 2 masses are equal, after the collision the moving one should stop and the other one should start moving. This is not happening. I also tried to write, in the if statment where the velocity should change due to the collision, small_vel=-1 and big_vel=0 and it worked fine.

Advertisement

Answer

It seems to me that the problem is due to these two lines:

JavaScript

Here big_vel is updated according to the new value of small_vel which is not what we want. Saving the new value of small_vel in a temporary variable and restoring it after the assignment to big_vel seems to fix the problem:

JavaScript

To be honest I haven’t looked at the math stuff and I’m not sure this is exactly what you want but the result looks at least like the video of the wikipedia page.

On a side note you should have a look at this post: i get an pygame.error: video system not initialised error everytime i run the program to fix the bug in your code occuring when you close the window (the exception raised is not the same but the source of the problem and the solution to fix it are the same).

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