我正在做一个简单的乒乓球比赛,但是当球从天花板上掉下来时,它不会来回弹跳。它刚刚离开屏幕。我无法弄清楚为什么会这样!我只关心球从屏幕的顶部和底部反弹,我希望它在直线路径上来回反弹。任何帮助表示赞赏!
编辑:我发现了问题!谢谢你的帮助!这是我的基本代码:
import math
import random
import sys, pygame
from pygame.locals import *
import ball
import colors
import paddle
# draw the scene
def draw(screen, ball1, paddle1) :
screen.fill((128, 128, 128))
ball1.draw_ball(screen)
paddle1.draw_paddle(screen)
#function to start up the main drawing
def main():
pygame.init()
width = 600
height = 600
screen = pygame.display.set_mode((width, height))
ball1 = ball.Ball(300, 1, 40, colors.YELLOW, 0, 5)
paddle1 = paddle.Paddle(250, 575, colors.GREEN, 100, 20)
while 1:
for event in pygame.event.get():
if event.type == QUIT: sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
paddle1.update_paddle('right', 20)
if event.key == pygame.K_LEFT:
paddle1.update_paddle('left', 20)
ball1.test_collide_top_ball(600)
ball1.test_collide_bottom_ball(0)
ball1.update_ball()
draw(screen, ball1, paddle1)
pygame.display.flip()
if __name__ == '__main__':
main()
这是我的球类/方法的代码:
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, coll_height):
if (self.y >= coll_height):
self.dy *= -1
答案 0 :(得分:1)
您的测试碰撞函数返回速度值。你永远不会在任何地方使用它。
您使用dx=0
dy=5
调用更新球。
最好不要在碰撞后返回一个值,而是将dx
和dy
放在对象中。所以它会变成:
class Ball:
def __init__(self, x, y, radius, color):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.dx = 0
self.dy = 5
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, coll_height):
if (self.y >= coll_height):
self.dy *= -1