Pygame 重力脚本 [英] Pygame Gravity Script
问题描述
我正在尝试使用 pygame 制作一个 python 脚本来模拟重力.问题是,我的播放器"一直卡在底部甚至没有弹跳一次.如果有帮助,我正在使用 python 3.4.1.这是我的代码:
I'm trying to make a python script with pygame to simulate gravity. The problem is, my "player" keeps getting stuck at the bottom without bouncing even once. I'm using python 3.4.1 if that helps. Here's my code:
import pygame
pygame.init()
disp_w = 800
disp_h = 600
disp = pygame.display.set_mode((disp_w,disp_h))
pygame.display.set_caption('Gravity')
player_x = disp_w/2
player_y = 0
player = pygame.image.load('images/player.png')
gravity = 0.1
speed = 0
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
player_y += speed
speed += gravity
if player_y > disp_h:
speed = speed * -0.7
disp.fill((0,0,0))
disp.blit(player,(player_x,player_y))
pygame.display.flip()
clock.tick(120)
推荐答案
在一个框架中,你会掉到地板下,比如说,1.0 个单位.然后您的速度变为 -0.7.
On one frame, you'll fall beneath the floor by, say, 1.0 unit. Your speed then goes to -0.7.
因此,在下一帧中,您最终会低于地板 0.3 个单位,然后再次将速度调至 +0.49.
On the next frame, therefore, you end up below the floor by 0.3 units and flip your speed again, to +0.49.
在下一帧中,您低于地板 0.79 个单位,然后再次翻转标志,依此类推.你永远不会出去.
On the following frame, you're below the floor by 0.79 units and flip the sign again, and so on. You never get out.
试试:
if player_y > disp_h:
# stop the player at the floor
player_y = disp_h
speed = speed * -0.7
这篇关于Pygame 重力脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!