Quantcast
Viewing all articles
Browse latest Browse all 14360

Handling collision in Python using Pygame [duplicate]

I am creating a Pong clone as my first project while I follow a step-by-step guide. Along the way, I encountered problems when creating a handle for collisions with the ball and paddles.

When running the code, an attribute error occurred from the paddle height in the condition statements

    def handle_collision(ball, left_paddle, right_paddle):        if ball.y + ball.radius >= HEIGHT:            ball.y_VELOCITY *= -1        elif ball.y - ball.radius <= 0:            ball.y_VELOCITY *= -1    if ball.x_VELOCITY < 0:        if ball.y >= left_paddle.y and ball.y <= left_paddle.y + left_paddle.height:            if ball.x - ball.radius <= left_paddle.x + left_paddle.width:                ball.x_VELOCITY *= -1    else:        if ball.y >= right_paddle.y and ball.y <= right_paddle.y + right_paddle.height:            if ball.x + ball.radius >= right_paddle.x:                ball.x_VELOCITY *= -1

The reasons for error were mentioned as:

AttributeError: 'Paddle' object has no attribute 'height'

and...

AttributeError: 'Paddle' object has no attribute 'width'

When adding parentheses to the conditions, the problem seemed to go away. Here was what I changed

if ball.x_VELOCITY < 0:    if (ball.y >= left_paddle.y) and (ball.y <= left_paddle.y + left_paddle.height):        if ball.x - ball.radius <= left_paddle.x + left_paddle.width:            ball.x_VELOCITY *= -1else:    if (ball.y >= right_paddle.y) and (ball.y <= right_paddle.y + right_paddle.height):        if ball.x + ball.radius >= right_paddle.x:            ball.x_VELOCITY *= -1

I do not know if this is a temporary fix or a clear solution to the problem. Could this be explained?


Viewing all articles
Browse latest Browse all 14360

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>