如何让Pygame检测图像周围的边界?

时间:2019-04-15 15:33:43

标签: python pygame

Pygame仅识别从(0,0)绘制图像的像素。

我在文档中找不到任何内容,在这里也找不到任何内容。所以我希望可以在这里得到一些信息。

import pygame

pygame.init()


windowWidth = 1280
windowHeight = 720

vel = 10.0

gameDisplay = pygame.display.set_mode((windowWidth,windowHeight))
pygame.display.set_caption('Heart Attack')

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()
crashed = False
charImg = pygame.image.load('heart1.png')

#function to draw the character at a certain place
def heart(x,y):
    gameDisplay.blit(charImg, (x,y))

#stackoverflow
class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location

#stackoverflow
BackGround = Background('background_image.png', [0,0])

x = 0
y = 0

gameDisplay.fill(white)
gameDisplay.blit(BackGround.image, BackGround.rect)

#collision detection for the borders, as well as moving the character around
while not crashed:
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        if x <= 0:
            x = x + 1
        else:
            x -= vel
    if keys[pygame.K_RIGHT]:
        if x >= windowWidth:
            x = x - 1
        else:
            x += vel
    if keys[pygame.K_UP]:
        if y <= 0:
            y = y + 1
        else:
            y -= vel
    if keys[pygame.K_DOWN]:
        if y >= windowHeight:
            y = y - 1
        else:
            y += vel
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
    #stackoverflow
    gameDisplay.blit(BackGround.image, BackGround.rect)
    heart(x,y)


    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()

我需要pygame来检测图像周围的边界,因此我可以检查图像是否接触到墙壁或平台。我知道sprite对象,但是我不知道如何使用它,我也不了解。在这种情况下会需要吗?

谢谢!

0 个答案:

没有答案