如何使角色在Pygame中跳跃?

时间:2020-06-04 20:36:00

标签: python pygame

我正在尝试制作平台游戏,但我想让圆圈跳起来,但是每当尝试进行跳跃时,都会出现以下错误,我发现了进行跳跃的各种方法,但没有一种起作用。 我认为错误是我每次跳转时都会出现浮点数,而draw方法不能包含浮点数,只能是整数

这是游戏代码:

import pygame
import os
import time
import random
pygame.font.init()

Width, Height = 1280, 720
win = pygame.display.set_mode((Width, Height))
pygame.display.set_caption("Parkour Ball")

BG = pygame.image.load(os.path.join("assets", "Background.jpg"))

class Ball:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def draw(self, window):
        pygame.draw.circle(window, (255,0,0), (self.x, self.y), 25)

def main():
    run = True
    FPS = 60
    clock = pygame.time.Clock()
    level = 0
    lives = 10
    main_font = pygame.font.SysFont("comicsans", 50)
    lost_font = pygame.font.SysFont("comicsans", 60)

    spikes = []
    holes = []
    hammers = []
    platforms = []
    enemies = []

    player_vel = 5
    jump = False
    jumpCount = 10
    player = Ball(300, 450)

    lost = False
    lost_popup = 0

    def redraw():
        win.blit(BG, (0,0))
        player.draw(win)

        pygame.display.update()

    while run:
        clock.tick(FPS)
        redraw()

        if lives == 0:
            lost = True
            lost_popup += 1

        if lost:
            if lost_popup > FPS * 3:
                run = False
            else:
                continue

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

        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player.x - player_vel - 25 > 0:
            player.x -= player_vel
        if keys[pygame.K_RIGHT] and player.x + player_vel + 25 < Width:
            player.x += player_vel
        if keys[pygame.K_w]and player.y - player_vel > 0: #up
            player.y -= player_vel
        if keys[pygame.K_s] and player.y + player_vel < Height: #down
            player.y += player_vel
        if not(jump):
            if keys[pygame.K_SPACE]:
                jump = True
        else:
            if jumpCount >= -10:
                neg = 1
                if jumpCount < 0:
                    neg = -1
                player.y -= (jumpCount ** 2) / 2 * neg
                jumpCount -= 1

main()

1 个答案:

答案 0 :(得分:1)

pygame.draw.circle()的坐标必须是整数值。 round()浮点坐标为整数坐标:

pygame.draw.circle(window, (255,0,0), (self.x, self.y), 25)

pygame.draw.circle(window, (255,0,0), (round(self.x), round(self.y)), 25)