¿Cómo rotar una imagen (reproductor) en la dirección del mouse?

Resuelto Rami Menai asked hace 4 años • 2 respuestas

Estoy pensando en hacer un juego de disparos en 2D en pygame y quiero que mi jugador (Player_1) apunte a la dirección del mouse. Busqué una solución durante horas y probé todas las soluciones que pude encontrar, pero ninguna funcionó, ¿podrían ayudarme? ? Aquí está mi código:

import pygame, sys, os
from pygame.locals import *
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()
#Exit settings
def quit():
  pygame.quit()
  sys.quit()
def events():
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
            quit()

#IDS
CLOCK=pygame.time.Clock()
FPS=120
DS=pygame.display.set_mode((0,0), pygame.FULLSCREEN)
pygame.display.set_caption("Shooting simulator")
W,H=DS.get_size()
P_X=W/2-50
P_Y=H/2-50

#Colors
Red=pygame.Color("#FF0000")
Blue=pygame.Color("#0000FF")
Green=pygame.Color("#00FF00")
Black=pygame.Color("#000000")
White=pygame.Color("#FFFFFF")

#IGT(in game things)
Player_1=pygame.image.load("Img/Player_1.png").convert()

def game_loop():
  while True:
    events()

    DS.fill(White)
    DS.blit(Player_1,(P_X,P_Y))
    pygame.display.flip()
game_loop()

Este es mi jugador(Player_1)

Realmente apreciaré toda la ayuda.

Rami Menai avatar Oct 29 '19 15:10 Rami Menai
Aceptado

Tienes que calcular el ángulo del vector desde el jugador hasta el mouse. obtenga la posición del mouse pygame.mouse.get_pos()y el rectángulo ( pygame.Rect) alrededor del jugador:

mx, my = pygame.mouse.get_pos()
player_rect = Player_1.get_rect(topleft=(P_X,P_Y))

Calcule el vector desde el jugador al mouse y calcule el ángulo del vector mediante math.atan2. El eje y debe invertirse ( -dy), ya que generalmente apunta hacia arriba, pero en el sistema de coordenadas PyGame el eje y apunta hacia abajo.

dx, dy = mx - player_rect.centerx, player_rect.centery - my
angle = math.degrees(math.atan2(-dy, dx)) - correction_angle

Además hay que restar un ángulo de corrección ( - correction_angle). El ángulo de corrección depende del Sprite . si el duende

mira hacia la derecha, el ángulo de corrección es 0: correction_angle = 0
mira hacia arriba, el ángulo de corrección es 90: correction_angle = 90
mira hacia la izquierda, el ángulo de corrección es 180: correction_angle = 180
mira hacia abajo, el ángulo de corrección es 270:correction_angle = 270

Gire el reproductor según pygame.transform.rotate()el ángulo alrededor de su centro:
(Consulte también ¿Cómo giro una imagen alrededor de su centro usando Pygame? )

rot_image = pygame.transform.rotate(Player_1, angle)
rot_image_rect = rot_image.get_rect(center=player_rect.center)

Ejemplo mínimo: repl.it/@Rabbid76/PyGame-RotateWithMouse

import math
import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
player = pygame.image.load("player.png").convert_alpha()

#   0 - image is looking to the right
#  90 - image is looking up
# 180 - image is looking to the left
# 270 - image is looking down
correction_angle = 90

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    player_pos  = window.get_rect().center
    player_rect = player.get_rect(center = player_pos)

    mx, my = pygame.mouse.get_pos()
    dx, dy = mx - player_rect.centerx, my - player_rect.centery
    angle = math.degrees(math.atan2(-dy, dx)) - correction_angle

    rot_image      = pygame.transform.rotate(player, angle)
    rot_image_rect = rot_image.get_rect(center = player_rect.center)

    window.fill((255, 255, 255))
    window.blit(rot_image, rot_image_rect.topleft)
    pygame.display.flip()

pygame.quit()
exit()

Rabbid76 avatar Oct 29 '2019 08:10 Rabbid76