如何将图像(播放器)旋转到鼠标方向?

时间:2019-10-29 08:38:49

标签: python pygame

我正在考虑在pygame中制作2D射击游戏,我想让我的玩家(Player_1)指向鼠标方向。我寻找了一个小时的解决方案,并尝试了所有我能找到的解决方案,但都没有成功,所以您可以请帮助我 ? 这是我的代码:

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()

This is my player(Player_1)

我将非常感谢所有帮助。

2 个答案:

答案 0 :(得分:1)

通过pygame.mouse.get_pos()和播放器周围的矩形(pygame.Rect)获取鼠标位置:

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

通过math.atan2计算玩家中心点与鼠标位置的夹角:

angle = math.degrees(math.atan2(player_rect.centery - mouse_pos[1],
                                mouse_pos[0]-player_rect.centerx)) + 90

通过pygame.transform.rotate()将播放器绕其中心旋转:
(另请参见How do I rotate an image around its center using Pygame?

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

此外,对每个像素alpha使用.convert_alpha()

请参见示例:

import math
import pygame

pygame.init()
DS = pygame.display.set_mode((640, 480))

Player_1=pygame.image.load("Img/Player_1.png").convert_alpha()

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

    DS.fill((255, 255, 255))

    mouse_pos   = pygame.mouse.get_pos()
    player_pos  = DS.get_rect().center
    player_rect = Player_1.get_rect(center = player_pos)

    angle = math.degrees(math.atan2(player_rect.centery - mouse_pos[1],
                                    mouse_pos[0]-player_rect.centerx)) + 90

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

    pygame.display.flip()

答案 1 :(得分:0)

这是您可以用来帮助的简单代码块。 它使用一些三角函数,并假定以下定义已定义: elsie是玩家

position = pygame.mouse.get_pos()
    angle = math.atan2(position[1] - (elsiepos[1] + 32), position[0] - (elsiepos[0] + 26))
    elsierot = pygame.transform.rotate(elsie, 360 - angle * 57.29)
    elsiepos1 = (elsiepos[0] - elsierot.get_rect().width / 2, elsiepos[1] - elsierot.get_rect().height / 2)
    screen.blit(elsierot, elsiepos1)

该块应该在检测到按键后立即出现,并且应该在绘制播放器之前出现,在这种情况下为elsie。