1 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
彈跳球的技巧是增加重力。重力總是加速 Y(垂直)速度朝向地板。
當(dāng)球下落時(shí),速度增加
隨著球上升,速度下降
當(dāng)球撞擊地面時(shí),速度反轉(zhuǎn)并且球“彈跳”。當(dāng)球速在頂部達(dá)到零時(shí),重力會反轉(zhuǎn)速度并將球拉向地面。
這是一個(gè)彈跳球的簡單示例:
import pygame as pg
from time import sleep, time
pg.init()
Height = Width = 500 # window dimensions
pg.display.set_caption("Bounce") # window title
win = pg.display.set_mode((Height, Width)) # create window
ball = {'x':Width/2, 'y':100, 'xs':3, 'ys':3 } # ball start position and speed
radius = 20 # ball radius
while True: # main loop
for event in pg.event.get(): # required for OS events
if event.type == pg.QUIT:
pg.quit()
pg.time.Clock().tick(30) # 30 FPS
win.fill((255, 255, 255)) # clear screen
pg.draw.circle(win, (200, 0, 0), (int(ball['x']), int(ball['y'])), 20) # draw ball
ball['x'] += ball['xs'] # move ball left \ right
ball['y'] += ball['ys'] # move ball up \ down
if ball['y'] >= Height - radius: ball['ys'] = -ball['ys'] # bounce on floor
else: ball['ys'] += .2 # accelerate toward floor, increase speed down, decrease up
if ball['x'] <= radius or ball['x'] > Width - radius: ball['xs'] = -ball['xs'] # bounce on wall
pg.display.update()
添加回答
舉報(bào)