【问题标题】:Pygame relative coordinates between two objects , OOPPygame两个对象之间的相对坐标
【发布时间】:2021-05-11 15:52:11
【问题描述】:

假设我有一个类,其中包含 __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.x, self.y))

现在的问题是 myRelativeObject.xmyRelativeObject.y 的值没有从 move() 函数中的变量 myObject.xmyObject.y 中获取。

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

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

myInstance = myObject('instanceName')

注意:

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

【问题讨论】:

    标签: python oop pygame python-3.9


    【解决方案1】:

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

    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))
    

    【讨论】:

    • 我不知道我的代码发生了什么,它仍在从 init 方法中获取值
    • 不,它在循环之外
    • hmmmm,我发现问题出在哪里!
    • 为了控制 object1 实例,我根据“名称”参数对它们进行了分类。例如:myinstance1 = myObject('objectname'),但后来我指的是那个对象而不是指那个实例。
    猜你喜欢
    • 1970-01-01
    • 2010-10-04
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多