首页 > 解决方案 > 我们如何让我们的玩家在pygame中跳转

问题描述

import pygame
import sys
from pygame import *
from pygame.locals import RESIZABLE

pygame.init()

WINDOW_SIZE = (800, 600)
screen = pygame.display.set_mode(WINDOW_SIZE, RESIZABLE, 32)

player_img = pygame.image.load('ClipartKey_738895_adobespark.png')
player_X = 130
player_Y = 500
player_change_X=0

def player():
    screen.blit(player_img, (player_X, player_Y))

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

        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                player_change_X = 0.3
            if event.key == K_LEFT:
                player_change_X = -0.3
            if event.key == K_SPACE:
                player_Y += 40
        elif event.type == KEYUP:
            if event.key == K_RIGHT:
                player_change_X = 0
            if event.key == K_LEFT:
                player_change_X = 0

    screen.fill((0, 200, 255))
    player()
    player_X += player_change_X

    pygame.display.update()

我想让玩家跳大约 4 年,但不能这样做。请告诉我我该怎么做,如果告诉任何功能,请告诉我它是什么以及它是如何做到的,因为我是 pygame 的新手。

标签: pythonpygame

解决方案


您可以使用像on_floor. 如果它在地板上(使用碰撞),那么它允许程序开始跳跃(使用另一个变量,比如y_speed。我通常让玩家像这样跳跃:

y_speed = 0
on_floor = False

# main loop
    if on_floor:
        if pygame.key.get_pressed()[K_SPACE]:
            y_speed = -40 # start the jump if space pressed
            # set to the value you used, but you should move according the the framerate
    if y_speed > -40 # speed limit
        y_speed += 1 # change the speed, to make a parabol-shape fall

    player.y += y_speed

此外,你可以用这个答案让玩家像这样跳跃,它做类似的工作。


推荐阅读