Вычисление угла относительно курсора мыши в Pygame с использованием Python

Чтобы найти угол между точкой в ​​Pygame и курсором мыши, вы можете использовать следующие методы:

Метод 1: использование тригонометрии

  1. Получите положение точки и курсора мыши с помощью модуля мыши Pygame.
  2. Вычислить разницу координат x и y между точкой и курсором мыши.
  3. Используйте функцию math.atan2(), чтобы вычислить угол между двумя точками в радианах.
  4. При необходимости преобразуйте угол в градусы с помощью функции math.grades().

Вот пример фрагмента кода:

import pygame
import math
pygame.init()
# Get the position of the point and the mouse cursor
point_pos = (x1, y1)  # Replace with the coordinates of your point
mouse_pos = pygame.mouse.get_pos()
# Calculate the difference in coordinates
diff_x = mouse_pos[0] - point_pos[0]
diff_y = mouse_pos[1] - point_pos[1]
# Calculate the angle in radians
angle_rad = math.atan2(diff_y, diff_x)
# Convert the angle to degrees
angle_deg = math.degrees(angle_rad)
print("Angle in degrees:", angle_deg)

Метод 2: использование класса math.Vector2Pygame

  1. Получите положение точки и курсора мыши с помощью модуля мыши Pygame.
  2. Создайте два объекта pygame.math.Vector2с позициями точки и курсора мыши.
  3. Используйте метод angle_to(), чтобы вычислить угол между двумя векторами.
  4. При необходимости преобразуйте угол в градусы с помощью функции math.grades().

Вот пример фрагмента кода:

import pygame
import math
pygame.init()
# Get the position of the point and the mouse cursor
point_pos = (x1, y1)  # Replace with the coordinates of your point
mouse_pos = pygame.mouse.get_pos()
# Create Vector2 objects
point_vec = pygame.math.Vector2(point_pos)
mouse_vec = pygame.math.Vector2(mouse_pos)
# Calculate the angle in radians
angle_rad = point_vec.angle_to(mouse_vec)
# Convert the angle to degrees
angle_deg = math.degrees(angle_rad)
print("Angle in degrees:", angle_deg)