Reputation:
Having a bit of trouble with pong collision detection. I made a class for Pong initialized my canvas the attributes of the window etc and the velocity of the pong ball. Created the paddles using images and then resized them to the paddle dimensions that I wanted using PIL same for the pong ball.
Right now im using the canvas.coords method to detect the current location of my paddles and ball. According to my CPSC page this is supposed to return four values the upper right left and lower right/left corners and i can then detect collisions using these.
However, it is only returning two values, and it detects collisions in the midpoint of the paddle all the way down the screen - as in say the paddle is at the very top in the middle of the screen and the ball is then passes in the center of the canvas it will detect a collision and change velocities. Relevant code for collisions posted below.
def animate_pong_ball(self):
self.C1.move(self.animated_ball, self.pong_dx, self.pong_dy)
x1, y1 = self.C1.coords(self.animated_ball)
if x1 <= 0:
self.pong_dx *= -1
elif x1 > WINDOW_WIDTH / 2:
self.pong_dx *= -1
if y1 <= 0:
self.pong_dy *= -1
elif y1 > WINDOW_HEIGHT:
self.pong_dy *= -1
def detect_collisions(self):
p1_x, p1_y = self.C1.coords(self.paddle_1)
p2_x, p2_y = self.C1.coords(self.paddle_2)
b_x, b_y = self.C1.coords(self.animated_ball)
if p1_x == b_x or p2_x == b_x:
self.pong_dx *= -1
if p1_y == b_y or p2_y == b_y:
self.pong_dy *= -1
Full code at http://pastebin.com/KfEkpsAN Know theres errors in there rough copy just trying to get collisions working properly at the moment and cannot figure out whats wrong
Upvotes: 2
Views: 1278
Reputation: 19174
As you discovered (and as is documented in correct docs), the number of coordinates returned by canvas.coords(x) depends on the type of x. For whatever reason, you created the paddles and ball as images, added to the canvas with .create_image. Images are displayed with respect to the x,y anchor point, which is the center of the image unless you specify otherwise.
To get proper bounding boxes for collision detection, either use filled rectangles and a filled circle for paddles and ball (which is what the original game did, and the easiest thing to do), so .coords(x) returns the bounding box, or calculate the bounding box yourself from the image center and known image size.
The proper intersection code for a rectangular paddle and circular ball whose y-coordinate is above the line depends on whether the x-coordinate of the center of the ball is within the end-points of the line (intersection if y distance is less than radius), less than the radius outside the line (so the ball might hit the corner), or farther away (no intersection).
Upvotes: 2