Pygame move image in a certain direction

Viewed 42

The image should move from the top left corner to the bottom right corner. and vice versa. This works if the width and height of the screen are the same. If the width is larger, the image lands above the lower right corner

def basisfunktion(self,j):
    self.rect.x, x1 = self.li[j] ,self.li[j]        
    self.rect.y, y1 = self.li[j + 2] , self.li[j + 2]
    x2 = self.li[j+1]
    y2 = self.li[j+3]
    self.dx = x2 - x1
    self.dy = y2 - y1
    self.dist = math.sqrt(self.dx * self.dx + self.dy * self.dy)      
    
def update(self):       
    if self.rect.x >= 0 and self.rect.x <= screen_x and self.rect.y >= 0 and self.rect.y <= screen_y:            
       self.rect.x += self.speed *self.dx / self.dist
       self.rect.y += self.speed *self.dy / self.dist
       screen.blit(self.image,(self.rect.x, self.rect.y))
    else:           
       if self.index< (len(self.li)-4):
        self.index += 4
        self.rect.x = -1
        self.rect.y = -1 
        runbaby.basisfunktion(self.index)          
1 Answers

Sometimes you just have to read the documentation. See Pygame doesn't let me use float for rect.move, but I need it

Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. [...]

The fraction part of the coordinates gets lost when the new position of the object is assigned to the Rect object. If this is done every frame, the position error will accumulate over time.

If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect object. round the coordinates and assign it to the location (e.g. .topleft) of the rectangle:

def basisfunktion(self,j):
    self.x, x1 = self.li[j] ,self.li[j]        
    self.y, y1 = self.li[j + 2] , self.li[j + 2]
    self.rect.topleft = round(self.x), round(self.y) 
    x2 = self.li[j+1]
    y2 = self.li[j+3]
    self.dx = x2 - x1
    self.dy = y2 - y1
    self.dist = math.sqrt(self.dx * self.dx + self.dy * self.dy)      
    
def update(self):       
    if self.rect.x >= 0 and self.rect.x <= screen_x and self.rect.y >= 0 and self.rect.y <= screen_y:            
       self.x += self.speed *self.dx / self.dist
       self.y += self.speed *self.dy / self.dist
       screen.blit(self.image,(self.rect.x, self.rect.y))
    else:           
       if self.index< (len(self.li)-4):
        self.index += 4
        self.x = -1
        self.y = -1 
        runbaby.basisfunktion(self.index)   
    self.rect.topleft = round(self.x), round(self.y)       
Related