如果我的播放器精灵落在平台上,它会继续消失

时间:2018-07-18 19:31:34

标签: python-3.x pygame

我正在尝试构建我的第一个平台游戏。到目前为止,我可以左右移动,但是不幸的是,在实现碰撞和重力时遇到了无法修复的错误。如果它落在平台上,我的播放器会像蜘蛛侠一样不断消散。角色仍然存在,并降落在平台上,但不幸的是,他变得不可见。没有错误消息,我怀疑与冲突检查有关。

hits = pygame.sprite.spritecollide(object, allPlatforms, False)
    if hits:
        object.rect.y = hits[0].rect.top + 1
        object.vy = 0

    print(object.rect.midbottom)

它会在代码中打印出Players的位置,并且该播放器仍然存在并且可以移动,但是它没有显示。我做了什么使角色消失的事情?

import pygame
import random

WIDTH  = 500
HEIGHT = 400
FPS = 30


WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

playerImage = "blockBandit/BlockBandit.png"

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 50))
        self.image = pygame.image.load(playerImage).convert()
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)
        self.vx = 0
        self.vy = 0

class Platform(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((w, h))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y




pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Block Bandit")
clock = pygame.time.Clock()

allPlatforms = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

p1 = Platform(0, HEIGHT - 40, WIDTH, 40)
all_sprites.add(p1)
allPlatforms.add(p1)


def moveCharacter(object):

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        object.vx += -2
    if keys[pygame.K_RIGHT]:
        object.vx += 2

    object.vx = object.vx * 0.9

    if (abs(object.vx) < 1):
        object.vx = 0

    if (abs(object.vx) > 10):
        if(object.vx < 0):
            object.vx = -10
        else:
            object.vx = 10

    object.vy = object.vy + 1

    object.rect.x += object.vx
    object.rect.y += object.vy

    hits = pygame.sprite.spritecollide(object, allPlatforms, False)
    if hits:
        object.rect.y = hits[0].rect.top + 1
        object.vy = 0

    print(object.rect.midbottom)

running = True
while running:

    clock.tick(FPS)

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

    moveCharacter(player)
    #Update State
    all_sprites.update()

    #Render
    screen.fill(BLACK)
    all_sprites.draw(screen)
    #screen.blit(player.icon, (20, 40))
    pygame.display.flip()

pygame.quit()

我做错什么了吗?谢谢!

1 个答案:

答案 0 :(得分:0)

rect的y属性与top坐标相同,因此在此处object.rect.y = hits[0].rect.top + 1将播放器精灵的顶部设置为平台精灵的顶部。而且,如果该平台稍后出现在sprite组中,则它将在播放器播放后变白,并且播放器将不可见。

只需将该行更改为object.rect.bottom = hits[0].rect.top + 1