bounce function in pygame

428 Views Asked by At
def bounce(self):
        self.velocity[0] = -self.velocity[0]
        self.velocity[1] = randint(-10,10)

Hey, I would like to recode this bounce function but I have no clue, how should I do it?

1

There are 1 best solutions below

0
Shufi123 On

According to physics, the best and most natural-looking result would be to not change self.velocity[1]. Assuming that self.velocity[0] is on the X-axis, and self.velocity[1] is on the Y-axis, then if you are bouncing into any wall on the X-axis (left or right), self.velocity[1] shouldn't change, just the velocity on the X-axis should get reversed. In case you'd want to do the same thing for collision on the Y-axis, you should just do the same but with self.velocity[1] instead of self.velocity[0].

A diagram of a ball bounce that keeps the same angle:

Diagram of ball bounce

On the other hand, if what you want is to make it bounce of in a random direction (which wouldn't look as natural), your current function is great (although if you're using pygame you could convert self.velocity into a Vector2 object to make it cleaner).