topleft from surface rect dont accept new tuple value
Question:
I create pygame screen.
import pygame
pygame.init()
screen = pygame.display.set_mode((330, 330))
Then i create an object of my own class and give him a tuple.
mc = MyClass((10, 10))
This class has a problem. topleft
from surface
don`t accept new tuple value.
class MyClass:
def __init__(self, pos):
self.surface = pygame.Surface((100, 100))
self.surface.get_rect().topleft = pos
print(pos) # (10, 10)
print(self.surface.get_rect().topleft) # (0, 0)
How can i solve this problem?
Answers:
A Surface has no position and the rectangle is not an attribute of the Surface. The get_rect()
method creates a new rectangle object with the top left position (0, 0) each time the method is called. The instruction
self.surface.get_rect().topleft = pos
only changes the position of an object instance that is not stored anywhere. When you do
print(self.surface.get_rect().topleft)
a new rectangle object will be created with the top left coordinate (0, 0). You have to store this object somewhere. Then you can change the position of this rectangle object instance:
class MyClass:
def __init__(self, pos):
self.surface = pygame.Surface((100, 100))
self.rect = self.surface.get_rect()
self.rect.topleft = pos
print(self.rect.topleft)
I create pygame screen.
import pygame
pygame.init()
screen = pygame.display.set_mode((330, 330))
Then i create an object of my own class and give him a tuple.
mc = MyClass((10, 10))
This class has a problem. topleft
from surface
don`t accept new tuple value.
class MyClass:
def __init__(self, pos):
self.surface = pygame.Surface((100, 100))
self.surface.get_rect().topleft = pos
print(pos) # (10, 10)
print(self.surface.get_rect().topleft) # (0, 0)
How can i solve this problem?
A Surface has no position and the rectangle is not an attribute of the Surface. The get_rect()
method creates a new rectangle object with the top left position (0, 0) each time the method is called. The instruction
self.surface.get_rect().topleft = pos
only changes the position of an object instance that is not stored anywhere. When you do
print(self.surface.get_rect().topleft)
a new rectangle object will be created with the top left coordinate (0, 0). You have to store this object somewhere. Then you can change the position of this rectangle object instance:
class MyClass:
def __init__(self, pos):
self.surface = pygame.Surface((100, 100))
self.rect = self.surface.get_rect()
self.rect.topleft = pos
print(self.rect.topleft)