如何让球留在Pygame的屏幕上

时间:2017-08-04 04:59:21

标签: python python-2.7 pygame

我是编码,python和pygame的新手。我试图让球从屏幕上掉下来,在两侧反弹,直到慢慢失去能量并停留在页面底部。我得到了大部分工作,我的球反弹并失去了能量,但当速度减慢并击中底部边缘时,它会卡住并慢慢向下移出屏幕。完全不明白为什么,如果有人能告诉我我做错了什么,或者我需要添加到我的代码中,那将会有所帮助。谢谢!

import pygame
from math import  pi

pygame.init()

red = (255,0,0)
black = (0,0,0)
white = (255,255,255)
blue = (0,0,255)

pygame.mouse.set_visible(0)
clock = pygame.time.Clock()

displaySize = (800,600)

screen = pygame.display.set_mode(displaySize)
gameon = True

dt = 0.05

m= 5

ball_r = 30

ball_x = 100
ball_y = 500

ball_vx = 50
ball_vy = -50

g = 10

while gameon == True:

    Dy = 0.05*ball_vy*ball_vy
    Dx = 0.05*ball_vx*ball_vx

    Fy = m*g + Dy
    Fx = -Dx

    ay = Fy/m
    ax = Fx/m

    ball_vy += ay*dt
    ball_vx += ax*dt

    ball_x +=ball_vx*dt
    ball_y +=ball_vy*dt

    if ball_x <= ball_r or ball_x >= displaySize[0]-ball_r:
        ball_vx *=-1
    if ball_y <= ball_r or ball_y >= displaySize[1] - ball_r:
        ball_vy *=-1

    pos = pygame.mouse.get_pos()

    screen.fill(red)

    pygame.draw.circle(screen, white,(pos[0],pos[1]),30,0)

    pygame.draw.circle(screen,    blue,(long(round(ball_x)),long(round(ball_y))),ball_r,0)

    pygame.display.update()

    clock.tick(60)

    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

1 个答案:

答案 0 :(得分:0)

问题出现在以下声明中:

if ball_y <= ball_r or ball_y >= displaySize[1] - ball_r:
    ball_vy *=-1

实际上,您设置的条件是ball_y在第二次反弹后立即变得比displaySize[1]-ball_r更大。

这是一个解决方案;在ball_y试图变得大于displaySize[1]时,只需将ball_y的值设置为displaySize[1]。用以下行替换上面的行:

if ball_y <= ball_r or ball_y >= displaySize[1] - ball_r:
    ball_y = displaySize[1]- ball_r 
    ball_vy *= -.7

我还将ball_vy的速度改为.7。您可以根据自己的需要进行更改。