1
我正在爲我的學校項目設計2D遊戲。Pygame:兩幅圖像的碰撞
我有3張圖片,一個是播放器,另外兩個是實例(咖啡和電腦)。我想要做的是,當玩家圖像與兩個實例中的一個碰撞時,我希望程序打印某些東西。
我不確定圖像碰撞是否可能。但我知道rect碰撞是可能的。然而,在幾次失敗的嘗試後,我無法設法讓我的圖像改變。有人請幫助我。這裏是我的源代碼:
import pygame
import os
black=(0,0,0)
white=(255,255,255)
blue=(0,0,255)
class Player(object):
def __init__(self):
self.image = pygame.image.load("player1.png")
self.image2 = pygame.transform.flip(self.image, True, False)
self.coffee=pygame.image.load("coffee.png")
self.computer=pygame.image.load("computer.png")
self.flipped = False
self.x = 0
self.y = 0
def handle_keys(self):
""" Movement keys """
key = pygame.key.get_pressed()
dist = 5
if key[pygame.K_DOWN]:
self.y += dist
elif key[pygame.K_UP]:
self.y -= dist
if key[pygame.K_RIGHT]:
self.x += dist
self.flipped = False
elif key[pygame.K_LEFT]:
self.x -= dist
self.flipped = True
def draw(self, surface):
if self.flipped:
image = self.image2
else:
im = self.image
for x in range(0, 810, 10):
pygame.draw.rect(screen, black, [x, 0, 10, 10])
pygame.draw.rect(screen, black, [x, 610, 10, 10])
for x in range(0, 610, 10):
pygame.draw.rect(screen, black, [0, x, 10, 10])
pygame.draw.rect(screen, black, [810, x, 10, 10])
surface.blit(self.coffee, (725,500))
surface.blit(self.computer,(15,500))
surface.blit(im, (self.x, self.y))
pygame.init()
screen = pygame.display.set_mode((800, 600))#creates the screen
player = Player()
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
player.handle_keys() # movement keys
screen.fill((255,255,255)) # fill the screen with white
player.draw(screen) # draw the player to the screen
pygame.display.update() # update the screen
clock.tick(60) # Limits Frames Per Second to 60 or less
好的,我加入了變化,我讓玩家直接和咖啡。我在while循環之前放置了碰撞測試,並且如果self.rect.colliderect(self.rect_coffe): 打印「否」 只要我啓動程序,它會打印「否」。 我在做什麼錯?在'key handle'之後和'draw'之前的 – meowmar
。 – furas
您是否在'rect_coffe'中設置了咖啡位置?作爲默認矩形使用(x = 0,y = 0)。你總是可以'打印(self.rect,self.rect_coffe)'來查看職位。 – furas