[英]Why isn't the ball bouncing back?
我正在做一個簡單的乒乓球游戲,但是當球從天花板掉落時,它不會來回彈跳。 它只是從屏幕上消失了。 我不知道為什么會這樣! 我只關心球從屏幕頂部和底部彈起,我希望它沿直線路徑來回彈跳。 任何幫助表示贊賞!
編輯:我發現了問題! 感謝您的所有幫助!
這是我的基本代碼:
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
您的測試碰撞函數將返回速度值。 您永遠不會在任何地方使用它。
您用dx=0
dy=5
調用更新球。
與其在碰撞后返回a值,不如將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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.