python - 无法在 Pygame 无尽的跳线中使角色跳跃
问题描述
我正在尝试从谷歌重新创建恐龙游戏,我正处于让我的角色跳跃的阶段,但我无法让它工作,所以我想知道是否有人可以帮助我让我的角色跳跃。我试图做的是使用一个for循环让播放器上升然后等待然后使用另一个for循环让它下降但是当我按下向上键让它跳转时它不会做任何事情也给我一个错误。这是我尝试跳转代码
for x in range(0, 60):
player_y -= player_vel
time.sleep(0.5)
for x in range(0, 60):
player_y += player_vel
解决方案
不要尝试在应用程序循环中使用附加循环来控制游戏。使用应用程序循环。添加变量is_jumping
adn jump_count
:
is_jumping = False
jump_count = 0
用于pygame.time.Clock
控制每秒帧数,从而控制游戏速度。
对象的方法tick()
以pygame.time.Clock
这种方式延迟游戏,循环的每次迭代消耗相同的时间段。见pygame.time.Clock.tick()
:
此方法应每帧调用一次。
这意味着循环:
clock = pygame.time.Clock() run = True while run: clock.tick(50)
每秒运行 50 次。
使用KEYDOWN
事件而不是pygame.key.get_pressed()
跳转:
run = True
while run:
clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and not is_jumping:
is_jumping = True
jump_count = 30
pygame.key.get_pressed()
返回一个包含每个键状态的列表。如果按住某个键,则该键的状态为True
,否则为False
。用于pygame.key.get_pressed()
评估按钮的当前状态并获得连续移动。
键盘事件(参见pygame.event模块)仅在按键状态更改时发生一次。KEYDOWN
每次按下某个键时,该事件发生一次。KEYUP
每次释放键时发生一次。将键盘事件用于单个操作。
根据应用循环中的is_jumping
adn改变播放器的位置:jump_count
while run:
# [...]
#movement code
if is_jumping and jump_count > 0:
if jump_count > 15:
player_y -= player_vel
jump_count -= 1
elif jump_count > 0:
player_y += player_vel
jump_count -= 1
is_jumping = jump_count > 0
完整示例:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Infinite Runner")
#defines the paremeters for the wall
wall_x = 800
wall_y = 300
wall_width = 20
wall_height = 20
score = 0
player_x = 400
player_y = 300
player_width = 40
player_height = 60
player_vel = 5
is_jumping = False
jump_count = 0
#where the main code is run
print(score)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and not is_jumping:
is_jumping = True
jump_count = 30
#movement code
if is_jumping and jump_count > 0:
if jump_count > 15:
player_y -= player_vel
jump_count -= 1
elif jump_count > 0:
player_y += player_vel
jump_count -= 1
is_jumping = jump_count > 0
#draws the player and the coin
screen.fill((0,0,0))
wall = pygame.draw.rect(screen, (244, 247, 30), (wall_x, wall_y, wall_width, wall_height))
player = pygame.draw.rect(screen, (255, 255, 255), (player_x, player_y, player_width, player_height))
pygame.display.update()
pygame.quit()
推荐阅读
- azure - Azure Web App 是否需要防火墙?
- powerbi - Power BI 查询连接到使用 HMAC 身份验证的 API
- angular - Angular 在应该只更新一个字段时同时更新所有字段
- azure - 检查应用服务从 Azure 容器存储库中提取映像的次数
- c++ - 关于c++函数中指针赋值的一个简单问题
- google-apps-script - 如何最好在不创建市场插件的情况下在域外共享谷歌网络应用程序
- sql - 嵌套分组查询的正确语法是什么?
- javascript - 使用 json 数据创建 html 表
- iis - IIS 和按目录压缩
- azure - 如何在 azure devops YAML 管道中将单个代理用于多个作业/阶段