In Pymunk, you can set gravity to make it so objects will go left or right (x) and up or down. (y)
I would like to change the gravity so objects collect in the centre, sort of like a centre of mass.
Is there any possible way to do this?
Asked
Active
Viewed 155 times
1 Answers
2
There is no built in way to "move" the gravity. Instead you have to do it manually, e.g. for each body calculate the gravity direction (and magnitude) and then apply it as a force each simulation step.
One way to do it is to create a custom velocity function, that you set on all the objects that you want to be affected by the gravity. It is documented here: http://www.pymunk.org/en/latest/pymunk.html#pymunk.Body.velocity_func
def custom_gravity_velocity(body, gravity, damping, dt):
g = ... code to calculate the gravity you want
# Call the default velocity function with the new gravity
pymunk.Body.update_velocity(body, g, damping, dt)
body.velocity_func = custom_gravity_velocity
I added a full example to the Pymunk github here: https://github.com/viblo/pymunk/blob/master/examples/planet.py

viblo
- 4,159
- 4
- 20
- 28
-
Could you provide an example in code? I'm fairly new to Pymunk. – daysant Aug 14 '21 at 14:44
-
1Ok, I have expanded the answer now. – viblo Aug 16 '21 at 12:44