球为什么不反弹? [英] Why isn't the ball bouncing back?
问题描述
我正在制作一个简单的乒乓球游戏,但是当球从天花板上掉下来时,它不会来回弹跳.它只是从屏幕上消失.我无法弄清楚为什么会这样!我只关心球从屏幕的顶部和底部弹起,我希望它以直线路径来回弹跳.任何帮助表示赞赏!
I'm making a simple pong game, but when the ball drops from the ceiling, it doesn't bounce back and forth. It just goes off the screen. I can't figure out why this is happening! I am only concerned with the ball bouncing off the top and bottom of the screen and I want it to bounce back and forth in a straight path. Any help is appreciated!
我发现了问题!感谢大家的帮助!
I've found the problem! Thanks for all the help!
这是我的基本代码:
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()
这是我的球类/方法代码:
And here is my code for the 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, coll_height):
if (self.y >= coll_height):
self.dy *= -1
推荐答案
您的测试碰撞函数返回速度值.你永远不会在任何地方使用它.
Your test collide functions return the value of velocity. You never use it anywhere.
您使用 dx=0
dy=5
调用更新球.
You call the update ball with dx=0
dy=5
.
与其在碰撞后返回 a 值,不如将 dx
和 dy
保存在对象中.所以它会变成:
Instead of returning the a value after collision, it would be better to hold the dx
and dy
in the object. So it would become:
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
这篇关于球为什么不反弹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!