在pygame中处理重叠对象上的单击

2024-09-30 00:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pygame构建一个非常简单的isometric游戏原型

因为我对pygame和游戏开发非常陌生,所以我不确定如何处理单击多个具有重叠rect的对象。游戏中的泥砖“堆叠”在一起,看起来就像一块单独的土地。玩家应该能够独立单击每个磁贴

你能告诉我怎么做吗

enter image description here


Tags: 对象rect游戏玩家原型pygame土地磁贴
1条回答
网友
1楼 · 发布于 2024-09-30 00:33:48

这个概念非常简单:

将所有可拖动对象存储在列表中。每当在对象上检测到单击时:

  1. 查找该对象的列表索引

  2. 检查是否选择了列表中索引大于当前对象(这意味着它们绘制在当前对象上方)的任何其他对象。 如果是,不要调用drag函数,如果不是,就调用它

  3. 在调用函数之前,请确保重新定位当前对象的列表索引;因为我们刚刚点击了它,它应该在所有其他对象之上, 因此remove将对象从列表中删除,并append将其删除到末尾

以下是该概念的实现:

import pygame

pygame.init()
screen = pygame.display.set_mode((500, 500))

objs = []

class Obj:
    def __init__(self, x, y, w, h, color):
        self.rect = pygame.rect.Rect(x, y, w, h)
        self.dragging = False
        self.color = color
        objs.append(self)

    def clicked(self, m_pos):
        return self.rect.collidepoint(m_pos)

    def set_offset(self, m_pos):
        self.dragging = True
        m_x, m_y = m_pos
        self.offset_x = self.rect.x - m_x
        self.offset_y = self.rect.y - m_y

    def drag(self, m_pos):
        m_x, m_y = m_pos
        self.rect.x = m_x + self.offset_x
        self.rect.y = m_y + self.offset_y

    def draw(self):
        pygame.draw.rect(screen, self.color, self.rect)

square1 = Obj(200, 170, 100, 100, (255, 0, 0))
square2 = Obj(150, 300, 100, 100, (0, 255, 0))
square3 = Obj(220, 30, 100, 100, (0, 0, 255))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                for square in objs:
                    if square.clicked(event.pos):
                        o = objs[objs.index(square)+1:]
                        if not any(s.clicked(event.pos) for s in o):
                            objs.remove(square)
                            objs.append(square)
                            square.set_offset(event.pos)
        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                for square in objs:
                    square.dragging = False
        elif event.type == pygame.MOUSEMOTION:
            for square in objs:
                if square.dragging:
                    square.drag(event.pos)
    screen.fill((255, 255, 255))
    for square in objs:
        square.draw()
    pygame.display.update()

输出:

enter image description here

相关问题 更多 >

    热门问题