python - How do I make the ball bounce off the paddle? -
i'm making basic pong game (paddle rectangle on bottom of screen , ball drops top of screen). want ball bounce when hits paddle. far, i've written code make ball bounce off top , bottom screen, i'm having trouble getting ball bounce off paddle.
i have modify parameters passed test_collide_ball method. if it’s current x values within range of paddle, bounces up.
i've been trying think of solution this, , i'm thinking if ball hits paddle's y coordinate (the height), bounces up. has within range of x coordinates make paddle (so width of paddle).
but when this, ball gets stuck in place. feedback appreciated! in advance.
here code ball class/methods:
import pygame class ball: def __init__(self, x, y, radius, color, dx, dy): self.x = x self.y = y self.radius = radius self.color = color self.dx = dx self.dy = dy def draw_ball(self, screen): pygame.draw.ellipse(screen, self.color, pygame.rect(self.x, self.y, self.radius, self.radius)) def update_ball(self): self.x += self.dx self.y += self.dy def test_collide_top_ball(self, top_height): if (self.y <= top_height): self.dy *= -1 def test_collide_bottom_ball(self, paddle): if (self.y == paddle.y) , (self.x >= paddle.x) , (self.x <= paddle.x + paddle.width): self.dy *= -1
what appears happening ball enters collision zone , reverses it's direction. ball still in collision zone, however, , reverses it's direction again.
what should debounce check. put simply, code prevents happening twice or more times (de-bouncing it).
from code example, ball's momentum reversed when enters paddle zone. might add boolean flag see if have detected ball entered zone. when first detected, set flag true. when ball moves outside of zone, set flag false. reverse ball's momentum if flag false.
so, (excusing rusty python)
def test_collide_bottom_ball(self, paddle): if (self.y == paddle.y) , (self.x >= paddle.x) , (self.x <= paddle.x + paddle.width) , (!self.hitpaddle): self.dy *= -1 self.hitpaddle = true else self.hitpaddle = false
and in entity:
self.hitpaddle = false
Comments
Post a Comment