我正在为学校设计2D游戏。

我有3张图片,一个是播放器,另外2个是实例(咖啡和计算机)。我想要做的是,当播放器图像与2个实例之一发生冲突时,我希望程序打印一些东西。

我不确定是否可能发生图像冲突。但是我知道可能会发生矩形碰撞。但是,经过几次失败的尝试,我无法使图像校正。有人请帮助我。这是我的源代码:

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

最佳答案

使用pygame.Rect()保持图像大小和位置。

图像(或更确切地说是pygame.Surface())具有函数get_rect(),该函数返回具有图像大小(和位置)的pygame.Rect()

self.rect = self.image.get_rect()


现在您可以设置开始位置,即。 (0, 0)

self.rect.x = 0
self.rect.y = 0

# or

self.rect.topleft = (0, 0)

# or

self.rect = self.image.get_rect(x=0, y=0)


Rect使用左上角作为(x,y))。

用它来改变位置

self.rect.x += dist


并绘制图像

surface.blit(self.image, self.rect)


然后可以测试碰撞

if self.rect.colliderect(self.rect_coffe):




顺便说一句:现在class Player看起来几乎像pygame.sprite.Sprite :)

关于python - Pygame:碰撞两个图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39929640/

10-12 13:12
查看更多