gpt4 book ai didi

python - 如何针对此特定代码在 Pygame 中模拟跳跃

转载 作者:太空宇宙 更新时间:2023-11-04 04:20:21 26 4
gpt4 key购买 nike

我一直试图在Pygame代码中模拟跳转,但未能成功实现。有一个尺寸为 10 x 10 的矩形,我希望该矩形在按下 SPACE 时跳转。我暂时让这段代码不受重力影响。

import pygame
pygame.init()
ScreenLenX = 1000
ScreenLenY = 500
win = pygame.display.set_mode((ScreenLenX, ScreenLenY))
pygame.display.set_caption("aman")
run = True
Xcord = 100
Ycord = 100
length = 10
height = 10
vel = 2
xmove = 1
ymove = 1
while run:
#pygame.time.delay(1)
for event in pygame.event.get():
print(event)
if event.type ==pygame.QUIT:

run = False

if keys[pygame.K_RIGHT] and Xcord <= ScreenLenX-length:
Xcord += vel
if keys[pygame.K_LEFT] and Xcord >= 0:
Xcord -= vel

if keys[pygame.K_UP] and Ycord >= 0:
Ycord -= vel
if keys[pygame.K_DOWN] and Ycord <= ScreenLenY - height:
Ycord += vel
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (Xcord, Ycord, length, height))
keys = pygame.key.get_pressed()


pygame.display.update()
pygame.quit()

最佳答案

参见 How to make a character jump in Pygame? .在主循环之前添加一个变量jump并用0初始化:

jump = 0  
while run:
# [...]

仅在 pygame.K_SPACE 上使用react,前提是允许玩家跳跃并留在地面上。如果满足,则将 jump 设置为所需的“跳跃”高度:

if keys[pygame.K_SPACE] and Ycord == ScreenLenY - height:
jump = 300

只要 jump 大于 0,就在主循环中向上移动玩家并减少 jump 相同的量。
如果玩家不跳跃,让他从黎明坠落,直到他到达地面:

 if jump > 0:
Ycord -= vel
jump -= vel
elif Ycord < ScreenLenY - height:
Ycord += 1

查看演示,其中我将建议应用到您的代码中:

import pygame
pygame.init()

ScreenLenX, ScreenLenY = (1000, 500)
win = pygame.display.set_mode((ScreenLenX, ScreenLenY))
pygame.display.set_caption("aman")
Xcord, Ycord = (100, 100)
length, height = (10, 10)
xmove, ymove = (1, 1)
vel = 2
jump = 0

run = True
clock = pygame.time.Clock()
while run:
#clock.tick(60)
for event in pygame.event.get():
print(event)
if event.type ==pygame.QUIT:
run = False

keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and Xcord <= ScreenLenX-length:
Xcord += vel
if keys[pygame.K_LEFT] and Xcord >= 0:
Xcord -= vel

if keys[pygame.K_SPACE] and Ycord == ScreenLenY - height:
jump = 300

if jump > 0:
Ycord -= vel
jump -= vel
elif Ycord < ScreenLenY - height:
Ycord += 1

win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (Xcord, Ycord, length, height))

pygame.display.update()

关于python - 如何针对此特定代码在 Pygame 中模拟跳跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54595777/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com