我正在pygame上玩遊戲,我希望有一個受重力影響的玩家。Pygame:測試實體間碰撞的方法
我需要一個代碼,可以像這個 -
如果玩家沒有與塊碰撞: player.y = player.y + 1
所以,當有一個塊在它之下,不要掉下來,否則會掉下來。
下面是代碼作爲一個整體:
import pygame,random
from pygame.locals import *
import itertools
pygame.init()
screen=pygame.display.set_mode((640,480))
class Block(object):
sprite = pygame.image.load("texture\\dirt.png").convert_alpha()
def __init__(self, x, y):
self.rect = self.sprite.get_rect(centery=y, centerx=x)
class Player(object):
sprite = pygame.image.load("texture\\playr.png").convert()
sprite.set_colorkey((0,255,0))
def __init__(self, x, y):
self.rect = self.sprite.get_rect(centery=y, centerx=x)
blocklist = []
player = []
while True:
screen.fill((25,30,90))
mse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == QUIT: exit()
key=pygame.key.get_pressed()
if key[K_LSHIFT]:
if event.type==MOUSEMOTION:
x=(int(mse[0])/32)*32
y=(int(mse[1])/32)*32
blocklist.append(Block(x+16,y+16))
else:
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
to_remove = [b for b in blocklist if b.rect.collidepoint(mse)]
for b in to_remove:
blocklist.remove(b)
if not to_remove:
x=(int(mse[0])/32)*32
y=(int(mse[1])/32)*32
blocklist.append(Block(x+16,y+16))
elif event.button == 3:
x=(int(mse[0])/32)*32
y=(int(mse[1])/32)*32
player=[]
player.append(Player(x+16,y+16))
for b in blocklist:
screen.blit(b.sprite, b.rect)
for p in player:
if p.rect.colliderect(blocklist):
print 'scoof'
screen.blit(p.sprite, p.rect)
pygame.display.update()
任何幫助表示讚賞!
您是否嘗試用'p.rect.top + = 1'替換'print'scoof''。 – Shashank
這個錯誤是從'如果p.rect.colliderect(blocklist)'引發的:' –