0

I had difficulty learning pygame. I made the character move behind the mouse. But I don't understand how to rotate the character image in the direction of the mouse.

I tried to calculate the cosine between the vector from the player to the mouse and the vector in the direction of the sprite's gaze, but nothing came out. The image is not rotated in the direction of the mouse.

Illustration

Calculation of rotation:

def rotate(self, pos: tuple):
    angle = 0
    mouse_x, mouse_y = pos[0], pos[1]
    dx, dy = mouse_x - self.x, mouse_y - self.y
    

    a = math.sqrt(dx * dx + dy * dy)
    b = math.sqrt(mouse_x * mouse_x + self.y * self.y)
    #c = math.sqrt(abs(a * a - b * b))

    angle = b / a

    self.rotate_ = math.degrees(angle)

Rendering:

def draw(self, pos) -> None:
    rotated_image = pygame.transform.rotate(self.image, self.rotate_)
    self.surface.blit(rotated_image, (self.surface_rect.centerx - 50, self.surface_rect.centery - 24))
mozway
  • 81,317
  • 8
  • 19
  • 49
Bilbab
  • 15
  • 3
  • `b / a` is not the angle. It's the cosine of the angle. You need some inverse function like `acos` to retrieve the angle once you know its cos. – Stef Feb 14 '22 at 11:00
  • Another problem is that `b / a` is infinite when `self.x == mouse_x`. Forget cosines. You should be using [atan2()](https://stackoverflow.com/q/35749246/1679849) for this. – r3mainer Feb 14 '22 at 11:02

0 Answers0