Код работает для меня, если я сохраняю center
исходного изображения
self.pos = pygame.math.Vector2(self.rect.centerx, self.rect.centery)
Код, используемый для тестирования:
Я сохраняю исходное изображение в self.original_image
и создаю повернутый изображение в self.image
import pygame
import random
import os
import math
# --- constants --- (UPPER_CASE_NAMES)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 25 # for more than 220 it has no time to update screen
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# --- classes --- (CamelCaseNames)
class Player(pygame.sprite.Sprite):
def __init__(self, game):
self.game = game
self.path = os.path.dirname(__file__)
self.imageFolder = os.path.join(self.path, "images")
pygame.sprite.Sprite.__init__(self)
self.original_image = pygame.image.load(os.path.join(self.imageFolder, "player.png")).convert_alpha()
#self.original_image = pygame.image.load("image.png")).convert_alpha()
self.image = self.original_image.copy()
self.rect = self.image.get_rect()
self.rect.center = (600, 500)
self.pos = (600,500)
def update(self):
if self.rect.y >= 940:
self.rect.y = 940
if self.rect.y <= 10:
self.rect.y = 10
if self.rect.x >= 1140:
self.rect.x = 1140
if self.rect.x <= 10:
self.rect.x = 10
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_w]:
self.rect.y -= 5
if keyPressed[pygame.K_s]:
self.rect.y += 5
if keyPressed[pygame.K_d]:
self.rect.x += 5
if keyPressed[pygame.K_a]:
self.rect.x -= 5
self.pos = pygame.math.Vector2(self.rect.centerx, self.rect.centery)
self.lookAtMouse()
def lookAtMouse(self):
mouseX, mouseY = pygame.mouse.get_pos()
relX, relY = mouseX - self.rect.x, mouseY - self.rect.y
angle = (180 / math.pi) * -math.atan2(relY, relX)
self.image = pygame.transform.rotate(self.original_image, int(angle))
self.rect = self.image.get_rect()
self.rect.center = self.pos
# --- functions --- (lower_case_names)
# --- main ---
pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )
player = Player(None)
# --- mainloop ---
clock = pygame.time.Clock()
running = True
while running:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
running = False
# --- changes/moves/updates ---
if not pygame.key.get_pressed()[pygame.K_SPACE]:
player.update()
# --- draws ---
screen.fill(BLACK)
screen.blit(player.image, player.rect)
pygame.display.flip()
# --- FPS ---
ms = clock.tick(FPS)
#pygame.display.set_caption('{}ms'.format(ms)) # 40ms for 25FPS, 16ms for 60FPS
fps = clock.get_fps()
pygame.display.set_caption('FPS: {}'.format(fps))
# --- end ---
pygame.quit()