如何站在地上时才跳? (蟒蛇)

时间:2017-07-10 19:37:59

标签: python pygame

截至目前,每当我按空格时,我都会跳。我怎么能这样做,所以我站在什么东西时才跳?我会创建一些变量,如STANDING和JUMPING吗?如果我这样做,如何在我的班级玩家中引用它们?这是我的代码,所有帮助表示赞赏。感谢大家。

import pygame as pg
import os
# create a variable for pg.math.Vector2
vec = pg.math.Vector2

TITLE = "Jumping 1"

WIDTH = 800
HEIGHT = 600

clock = pg.time.Clock()
FPS = 60

GREEN = (0, 255, 0)
LIGHTBLUE = (50, 200, 250)
RED = (255, 0, 0)

# Player properties
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
PLAYER_GRAVITY = 0.8

game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")

class Player(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = ((WIDTH / 2, HEIGHT / 2))
        # position, velocity, acceleration
        self.pos = vec(WIDTH / 2, HEIGHT / 2)
        self.vel = vec(0, 0)
        self.acc = vec(0, 0)

    def update(self):
        self.acc = vec(0, PLAYER_GRAVITY)
        keystate = pg.key.get_pressed()
        if keystate[pg.K_LEFT]:
            self.acc.x = -PLAYER_ACC
        if keystate[pg.K_RIGHT]:
            self.acc.x = PLAYER_ACC

        # apply friction
        self.acc.x += self.vel.x * PLAYER_FRICTION
        # equations of motion
        self.vel += self.acc
        self.pos += self.vel + 0.5 * self.acc
        # wrap around the sides of the screen
        if self.pos.x > WIDTH:
            self.pos.x = 0
        if self.pos.x < 0:
            self.pos.x = WIDTH

        self.rect.midbottom = self.pos

    def jump(self):
            self.vel.y = -20

player = Player()

class Platform(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((WIDTH, 50))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.center = ((WIDTH / 2, HEIGHT - 25))

platform = Platform()

def game_loop():
    pg.init()

    screen = pg.display.set_mode((WIDTH, HEIGHT))
    pg.display.set_caption(TITLE)

    all_sprites = pg.sprite.Group()
    all_sprites.add(player, platform)
    ground_sprite = pg.sprite.Group()
    ground_sprite.add(platform)

    running = True
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_SPACE:
                    player.jump()

        all_sprites.update()
        hits = pg.sprite.spritecollide(player, ground_sprite, False)
        if hits:
            player.pos.y = hits[0].rect.top or platform.rect.top
            player.vel.y = 0

        screen.fill(LIGHTBLUE)
        all_sprites.draw(screen)
        pg.display.flip()

        clock.tick(FPS)

    pg.quit()

game_loop()

1 个答案:

答案 0 :(得分:0)

在您的Player类中添加一个常设标志。然后在执行跳转检查之前按下空格,如果站立是真的话。如果站立是假的,那么基本上不要让跳跃发生:

labels

然后还要确保在跳跃完成后(即你降落的东西)将站立标志设置为真。