【问题标题】:I want to make my character jump in pygame and it's not working [duplicate]我想让我的角色在 pygame 中跳跃,但它不起作用 [重复]
【发布时间】:2023-04-07 14:43:02
【问题描述】:

我试图让我的角色跳跃,但它不起作用。因此,当我按 SPACE 时,y 位置应该递减以使我的玩家上升,而当他到达顶部时,我想让它再次下降。 我不知道该说什么该网站让我更详细地描述了这个问题,所以我在这里写字:)

这是现在的代码:

import pygame
import time
import random
#variabile
velPlayer = 1
xPlayer = 100
yPlayer = 100

#initializare
pygame.init()

screen = pygame.display.set_mode((1000,1000))
pygame.display.set_caption("Joculet")

#fundal
def ecranAlb():
    screen.fill((255,255,255))

#player   
def player():
    global xPlayer, yPlayer
    isJump = False
    jumpCount = 10
    pygame.draw.rect(screen,(0,0,253),(xPlayer,yPlayer,15,15))
    keys = pygame.key.get_pressed()

    if keys[pygame.K_RIGHT] and xPlayer < 971:
        xPlayer += velPlayer
    if keys[pygame.K_LEFT] and xPlayer > 0:
        xPlayer -= velPlayer
    if not(isJump):
        if keys[pygame.K_UP] and yPlayer > 0:
            yPlayer -= velPlayer
        if keys[pygame.K_DOWN] and yPlayer < 970:
            yPlayer += velPlayer
        if keys[pygame.K_SPACE]:
            isJump = True
    else:
        if jumpCount >= -10:
            neg = 1
            if jumpCount < 0:
                neg = -1

            yPlayer = (jumpCount ** 2) * 0.5 * neg
            jumpCount -= 1
        else:
            isJump = False
            jumpCount = 10

#main loop   
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    ecranAlb()
    player()
    pygame.display.flip()

pygame.quit()

【问题讨论】:

  • 不要仅仅为了写更多的词而写词,你可以写出你展示的代码的问题以及你想问的问题。

标签: python pygame


【解决方案1】:

isJumpjumpCount 必须在全局命名空间中的应用程序循环之前初始化。使用global statement 更改函数内全局命名空间中的变量:

isJump = False
jumpCount = 10

def player():
    global xPlayer, yPlayer, isJump, jumpCount 

    # [...] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    相关资源
    最近更新 更多