首页 > 解决方案 > 如何在pygame中获取图像的中心坐标

问题描述

我正在pygame中制作一个塔防游戏,我正在尝试制作一个拖放界面,玩家可以在其中选择塔并将其放置在任何想要的位置。然后我通过在每个塔周围画一个圈来表示它的范围来推进游戏。现在这里的问题是我需要圆圈在中心。由于我使用了塔的类,因此添加 x 和 y 坐标并没有帮助,因为我有不同大小的塔。我只需要知道如何在 pygame 中找到图像的中心。帮助将不胜感激。谢谢!

这是我的代码的类部分

class DragProperty():
    def __init__(self, img, x, y):
        self.img = img
        self.x = x
        self.y = y
        self.width = img.get_width()
        self.height = img.get_height()
        self.dragging = False

    def draw(self):
        screen.blit(self.img, (self.x, self.y))

    def startdrag(self):
        x = self.x
        y = self.y

        if mousex > self.x and mousex < self.x + self.width:
            if mousey > self.y and mousey < self.y + self.height:
                self.dragging = True
                self.offset_x = x - mousex
                self.offset_y = y - mousey

    def beingdragged(self):
        if self.dragging:
            self.x = mousex + self.offset_x
            self.y = mousey + self.offset_y

    def stopdrag(self):
        global balance
        global canDrag

        self.dragging = False
        canDrag = False

        balance -= 250

class AttackModule(DragProperty):
    def EnenmyinRange(self):
        pygame.draw.circle(screen, (0, 0, 0, 0), (self.x + 20, self.y + 20), 100)

    def attack(self):
        global balance
        
        balance += 50

#objects
MenuArcher = AttackModule(archertower, 5, 580)

标签: pythonpygame

解决方案


由于您已经定义了宽度和高度,您可以执行以下操作: self.x + self.width / 2self.y + self.height / 2


推荐阅读