I'm making a pong clone with pymunk in order to learn how the lib works. I got the ball bouncing off the walls correctly, but the paddle still refuses to stay inside the rectangle defined by the segments, one on each side of the screen.
def handle_input(self):
keys = pygame.key.get_pressed()
if keys[K_UP]: return Vec2d(0, 200)
elif keys[K_DOWN]: return Vec2d(0, -200)
else: return Vec2d(0, 0)
This function detects if K_UP
or K_DOWN
keys are pressed. If so, it returns a new vector with the desired velocity, which is then assigned to paddle.body.velocity
. The problem is, when the paddle reaches the top or bottom of the screen, instead of halting on those coordinates, it goes a little bit further up (or down) until the respective key is released, at which point it slowly returns in the opposite direction. The segment seems to offer some kind of resistance to the paddle, but only manages to stop it halfway out of the screen.
Why is this happening? How can I restrict the paddle's movement so that it only moves within the bounds established by the surrounding segments?
The problem is that you set the velocity directly on the body each frame. That will create problems for the collision solver and allow the paddle to move through the wall. Either you change it so that you apply an impulse instead, or you restrict its movement in another way.
I have a similar example in the examples folder of pymunk, breakout.py There I used a GrooveJoint to restrict its movement:
Full code here: https://github.com/viblo/pymunk/blob/master/examples/breakout.py
Note that setting the velocity every frame might have other side effects, but in your case I think it should work fine, just as the breakout example.