Collision of Two Rect

Ian Kelly ian.g.kelly at gmail.com
Fri May 3 19:42:30 EDT 2013


On Fri, May 3, 2013 at 4:23 PM, Alex Gardner <agardner210 at gmail.com> wrote:
> When rect A collides with rect B they stick when I am wanting A to bounce off of B.  I have tried different methods, but none seem to work.  My source is here:  http://pastebin.com/CBYPcubL
>
> The collision code itself is below:
> ------
> # Bounce off of the paddle
> if paddle_rect.colliderect(ball_rect):
>     y_vel*=-1
>     x_vel*=-1

What may be happening is that even though you reversed the direction
of the ball's movement, in the next frame the paddle and ball are
still detected as colliding, so they get reversed again.  If that kept
happening over and over again, then the ball would appear to be
"sticking".  You should check the current direction of movement after
detecting the collision and only reverse it if it is not already going
the proper direction.

The other thing that is suspicious about the code you posted is that
it has two different notions of the ball's position that are not
necessarily in agreement.  There is the ball_rect, and there are also
the x and y variables.  You center the ball_rect from the x and y
variables (somewhat awkwardly; see below), so at that point they would
agree, but then you update the x and y variables without updating the
rect accordingly.  So before you get to the collision detection code,
the position of the ball on screen and the one that is used for the
collision detection may be somewhat different from the *actual*
position of the ball.  You should be careful to make sure these
variables agree at all times -- or better yet, get rid of x and y
entirely, so that you only have one notion of the ball's position to
worry about.

By the way, this code:

     boundsball_rect = pygame.Rect(x,y,0,0)
     ball_rect.clamp_ip(boundsball_rect)

could more simply be expressed as:

     ball_rect.center = (x, y)

Because that's all you're doing here: updating the position of the
rect.  If you take my advice and do away with the x and y variables,
then your position updating code:

     x += x_vel
     y += y_vel

could simply be:

     ball_rect.move_ip(x_vel, y_vel)



More information about the Python-list mailing list