Answer the question
In order to leave comments, you need to log in
Why do objects move with a delay when moving_ip in Pygame?
Greetings. I placed the objects in the paygame (these are sprites in a group) in random places, getting random coordinates. Then I want to change these coordinates to create a chaotic movement in random directions. When I changed them like this: rect.x += 1, then I reset the previously assigned random coordinates to 0 x and the changes occurred from x = 0 for all objects. I remembered move_ip. But I don't understand why it works like this:
Depending on the set value, there is a delay before the start of movement, then the objects begin to move and accelerate after an equal time interval (measured by counting out loud and bending the fingers).
class Object(Sprite):
def __init__(self, screen, settings):
super().__init__()
self.screen = screen
self.screen_rect = self.screen.get_rect()
self.settings = settings
self.objects_amount = settings.objects_amount
self.image = pg.image.load('img/image.png').convert_alpha()
self.rect = self.image.get_rect()
self.x = float(self.rect.x)
self.y = float(self.rect.y)
self.width = self.rect.width
self.height = self.rect.height
def get_random_position(self):
""" Получаю список рандомных координат x и y """
start_position = self.width
x_end_position = self.settings.screen_width - self.width
y_end_position = self.settings.screen_height - self.height
pos_x = random.randint(start_position, x_end_position)
pos_y = random.randint(start_position, y_end_position)
return pos_x, pos_y
def set_random_position(self, humans_amount):
""" установить рандомные координаты """
positions_list = []
width = self.rect.width
height = self.rect.height
for i in range(objects_amount):
if not positions_list: # если пустой, то добавить первое значение
rand_x, rand_y = self.get_random_position()
positions_list.append((rand_x, rand_y))
elif positions_list:
rand_x, rand_y = self.get_random_position()
positions_list.append((rand_x, rand_y))
return positions_list
def update(self):
self.x += 0.01
self.rect.move_ip(self.x,self.x) # одинаковые значения просто пока разбираюсь
Answer the question
In order to leave comments, you need to log in
You have 60 FPS, which means 60 update calls per second, which means x every second increases by - 0.6px (0.01 * 60). It is also worth considering that integer arithmetic is used in pygame.Rect calculations , i.e. move_ip won't move your character if current x < 1. So while x gets to 1, you end up with a delay of ~2 seconds. If we take the increment as 0.001, then the increase will be 0.06px, and x will gain one in ~16 seconds (1 / 0.06) and only after 16 seconds the character will start moving. To avoid delay, as you might have guessed, you need to initially set x to one
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question