pygame平台碰撞

时间:2013-07-12 22:40:06

标签: python pygame

我正在使用pygame中的平台游戏,以学习引擎。

我有它创建块的多个实例,并且我有一个可以以越来越快的速度下降的玩家对象。我怎样才能让玩家在击中阻挡时不会掉头?这是我的代码:

#imports
import pygame, sys
from pygame.locals import *

#init game
pygame.init()
screen = pygame.display.set_mode((640,480))
pygame.key.set_repeat(True) 
clock = pygame.time.Clock()

#classes
class playerClass:
    x = 100
    y = 100
    boundingBox_x = 32
    boundingBox_y = 32
    sprite = pygame.image.load("Image2.png").convert_alpha()

class Block(object):

    sprite = None

    def __init__(self, x, y):
        if not Block.sprite:
            Block.sprite = pygame.image.load("Image1.png").convert_alpha()
        self.rect = Block.sprite.get_rect(top=y, left=x)

#objects
playerObject = playerClass()
blocks = []
blocks.append(Block(0, 14*32))
blocks.append(Block(1*32, 14*32))
blocks.append(Block(2*32, 14*32))
blocks.append(Block(3*32, 14*32))
blocks.append(Block(4*32, 14*32))
blocks.append(Block(5*32, 14*32))
blocks.append(Block(6*32, 14*32))
blocks.append(Block(7*32, 14*32))
blocks.append(Block(8*32, 14*32))
blocks.append(Block(9*32, 14*32))
blocks.append(Block(10*32, 14*32))
blocks.append(Block(11*32, 14*32))
blocks.append(Block(12*32, 14*32))
blocks.append(Block(13*32, 14*32))
blocks.append(Block(14*32, 14*32))
blocks.append(Block(15*32, 14*32))
blocks.append(Block(16*32, 14*32))
blocks.append(Block(17*32, 14*32))
blocks.append(Block(18*32, 14*32))
blocks.append(Block(19*32, 14*32))

blocks.append(Block(0, 13*32))
blocks.append(Block(19*32, 13*32))
blocks.append(Block(0, 13*32))
blocks.append(Block(19*32, 13*32))
blocks.append(Block(0, 12*32))
blocks.append(Block(19*32, 12*32))
blocks.append(Block(0, 11*32))
blocks.append(Block(19*32, 11*32))
#colors
white = 255,255,255

#variables
up = False
down = False
right = False
left = False

xspeed = 0
yspeed = 0
gspeed = 0.2
#functions

#main loop
quitting = False
while quitting == False:
    for event in pygame.event.get():

#event processing
        if event.type == pygame.QUIT:
            quitting = True

#game logic
    yspeed += gspeed
    playerObject.y += yspeed
#drawing
    screen.fill((white))

    screen.blit(playerObject.sprite,(playerObject.x,playerObject.y))
    for block in blocks:
        screen.blit(block.sprite, block.rect)

    pygame.display.flip()

#ending
    clock.tick(60)

另外,我知道我正在使用大量代码来构建关卡。我正在研究一个系统来读取txt文件的级别。谢谢

1 个答案:

答案 0 :(得分:2)

执行此操作的简单方法是使用pygame.sprite模块,该模块专为此类设计而设计。

该页面上的示例显示了您要执行的大部分操作; pygame附带的Shooter示例显示了所有细节。

但简单地说:将BlockPlayer设为sprite.Sprite的两个子类,将所有Block放入精灵组而不只是列表,然后使用{{ 1}},这就是它的全部内容。


如果你想手动完成,那么<​​em> 就更难了。您需要像对每个块一样跟踪播放器的边界矩形,然后代替此:

spritecollideany(player, block_group)

...你这样做:

spritecollideany(player, block_group)

一般来说,player.rect.collidelist([block.rect for block in blocks]) != -1 所做的一切都是你自己做的 - 只需要大约两倍的代码。当然,你必须弄清楚你需要做的所有事情 - 使用sprite,精灵和团队的简单API几乎可以告诉你在大多数游戏中你要做的所有事情。