Home > Net >  Pygame - How can I rotate a surface so it is "looking" in the direction that it is travell
Pygame - How can I rotate a surface so it is "looking" in the direction that it is travell

Time:02-12

I have written a program so a rectangle sequentially moves in the direction of many vectors. Arbitrary Example.

How can I calculate the angle by which the surface must rotate so it is "looking" in the direction of the vector that it is travelling along.

    def __FindAngle(self, previous, next):
        angle2 = -math.degrees(math.atan2(next.y, next.x))
        angle1 = -math.degrees(math.atan2(previous.y, previous.x))
        if angle1 == angle2:
            return 0
        return round(angle2 - angle1 - self.TaxiCorrection)

This is my current attempt in doing so where previous is the previous vector of its path and next is the next vector of its path. (self.TaxiCorrection is the correction angle depending on the image's orientation)

I'm new to stack overflow so apologies if my question is not as clear.

CodePudding user response:

The angle of the object can be calculated from the direction vector. See How to know the angle between two vectors?
Be aware that the y-axis needs to be reversed because in the PyGame coordinate system the y-axis is pointing down:

angle = math.degrees(math.atan2(previous.y-next.y, next.x-previous.x))

See How do I rotate an image around its center using PyGame?:

def blitRotateCenter(target_surf, surf, center, angle):
    rotated_surf = pygame.transform.rotate(surf, angle)
    bounding_rect = rotated_image.get_rect(center = center)
    target_surf.blit(rotated_surf, bounding_rect)

See also How do I gently change the direction of movement when moving forward?, How to turn the sprite in pygame while moving with the keys and Image rotation while moving .

  • Related