Pygame 两个对象之间的相对坐标,OOP

问题描述

假设我有一个包含 __init__(self) 部分中的对象坐标的类,如下所示:

class myObject(object):
    def __init__(self,name):
        self.img = file1
        self.x = random.randrange(0,700)
        self.y = random.randrange(0,700)
        ...

然后,在另一种方法中,xy 不断变化:

    def move(self):
        surface.blit(self.img,(self.x,self.y))
        self.x += 0.2
        self.y += 1
        ...

现在,假设我们有另一个类,其中有另一个对象。但是这个对象的坐标与第一个对象的坐标有关:

class myRelativeObject(self):
    def __init(self):
        self.img = file2
        self.x = myObject('instanceName').x + 20
        self.y = myObject('instanceName').y + 30

    def blit(self):
        surface.blit(self.img,self.y))

现在的问题是 myRelativeObject.xmyRelativeObject.y 值不是从 myObject.x 函数中的变量 myObject.ymove()获取的。>

然而,它们取自随机生成__init__(self) 中的那些。 这使得第二个对象的坐标每帧随机重新生成。此外,我希望它们与 move() 函数中的那些相关联,以便当第一个对象移动时,第二个对象也随之移动。

让它成为第一个对象的实例:

myInstance = myObject('instanceName')

注意:

请记住,除 init 之外的类方法都在 while 循环中运行。

解决方法

不要取对象的坐标,而是让引用的对象本身成为一个属性:

class myRelativeObject(self):
    def __init(self):
        self.img = file2
        self.refObject = myObject('instanceName')
        self.relX = 20
        self.relY = 30

    def blit(self):
        x = self.refObject.x + self.relX
        y = self.refObject.y + self.relY
        surface.blit(self.img,(x,y))