Pygame relative coordinates between two objects , OOP

Viewed 103

Let's say that i have a class containg the object coordinates in the __init__(self) part like this :

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

Then, in another method, the x and y are being continuously changed :

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

Now , let's say that we have another class in which we have another object. But this object's coordinates are related to the coordinates of that first object :

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

The problem now is that the myRelativeObject.x and myRelativeObject.y values are not being taken from the varibales myObject.x and myObject.y in the move() function.

Yet, they are taken from those in the __init__(self) that are randomly generated. This makes the second object's coordinates being randomly regenerated every frame. Besides, i want them to be in relation with those in the move() function so that when the first object moves, the second one moves with it.

Let this be an instance of the first object:

myInstance = myObject('instanceName')

NOTE :

Keep in mind that the class methods except the init one, are running in a while loop.

1 Answers

Do not take the coordinates of the object, but make the referenced object an attribute itself:

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