스프라이트를 마우스쪽으로 회전하고 이동하려면 어떻게합니까?
내 코드에서 스프라이트의 좌표가 어디에 있는지 변경되지 않는 것 같아 혼란 스럽습니다. 퍼팅 (200, 200)
은 퍼팅 (900, 100000)과 동일합니다. 따라서 기본적으로 지정된 위치에서 스프라이트를 조정할 수 없습니다. 도울 수 있니?
크레딧을 Ann Zen에게 돌리는 중입니다.하지만 나에게 스프라이트 문제가 생겼습니다.
내 코드 :
import pygame
from math import atan2, degrees
# tank = pygame.image.load('Sprite0.png')
wn = pygame.display.set_mode((400, 400))
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Sprite0.png')
self.x = 0
self.y = 0
self.rect = self.image.get_rect()
def point_at(self, x, y):
rotated_image = pygame.transform.rotate(self.image, degrees(atan2(x-self.rect.x, y-self.rect.y)))
new_rect = rotated_image.get_rect(center=self.rect.center)
wn.fill((255, 255, 255))
wn.blit(rotated_image, new_rect.topleft)
player = Player()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.MOUSEMOTION:
player.point_at(*pygame.mouse.get_pos())
# wn.blit(tank, Player)
pygame.display.update()
답변
이미지 (플레이어)를 마우스 방향으로 회전하는 방법에 대한 답변을 읽으십시오 . 조심스럽게. 각도 계산
degrees(atan2(x-self.rect.x, y-self.rect.y))
우연히 작동합니다. 작동하기 때문에 atan2(x, y) == atan2(-y, x)-pi/2
.
벡터의 각도 ( x , y )는 atan2(y, x)
입니다. y 축은 -y
일반적으로 위쪽을 가리 키지 만 PyGame 좌표계에서는 y 축이 아래쪽을 가리 키므로 y 축을 반전해야합니다 ( ). Sprite가 위쪽을 가리키고 다음과 같이 계산할 가능성이 높습니다 .
angle = degrees(atan2(self.rect.y - y, x - self.rect.x)) - 90
각기
direction = pygame.math.Vector2(x, y) - self.rect.center
angle = direction.angle_to((0, -1))
두 점 사이의 각도를 아는 방법 도 참조하십시오 .
스프라이트 에 저장된 위치에 그려 rect
속성. x
및 y
속성 이 전혀 필요하지 않습니다 . 사각형 ( rect
) 의 위치 만 설정하면됩니다 . 생성자에 x 및 y 인수를
추가 합니다.
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Sprite0.png')
self.rect = self.image.get_rect(center = (x, y))
메서드를 추가 move
하고 사용 pygame.Rect.move_ip하여 Sprite 의 위치를 변경합니다 .
class Player(pygame.sprite.Sprite):
# [...]
def move(self, x, y):
self.rect.move_ip(x, y)
Spritemove
의 위치를 변경하려면을 호출 하십시오 .
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
player.move(0, -1)
if keys[pygame.K_s]:
player.move(0, 1)
if keys[pygame.K_a]:
player.move(-1, 0)
if keys[pygame.K_d]:
player.move(1, 0)
각기
keys = pygame.key.get_pressed()
player.move(keys[pygame.K_d]-keys[pygame.K_a], keys[pygame.K_s]-keys[pygame.K_w])
스프라이트는 항상 포함되어야한다 pygame.sprite.Group. 참조 pygame.sprite.Group.draw():
포함 된 Sprite를 Surface 인수에 그립니다. 이것은
Sprite.image
소스 표면과Sprite.rect
위치에 대한 속성을 사용합니다 .
추가 그룹 과 추가 스프라이트를 받는 그룹 :
player = Player(200, 200)
all_sprites = pygame.sprite.Group(player)
그룹의draw
모든 스프라이트 를 그리려면 호출 하십시오 .
all_sprites.draw(wn)
회전 된 이미지가 image
속성에 저장되어 있는지 확인하십시오 .
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.original_image = pygame.image.load('Sprite0.png')
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
def point_at(self, x, y):
direction = pygame.math.Vector2(x, y) - self.rect.center
angle = direction.angle_to((0, -1))
self.image = pygame.transform.rotate(self.original_image, angle)
self.rect = self.image.get_rect(center=self.rect.center)
# [...]
최소한의 예 :

import pygame
wn = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.original_image = pygame.image.load('Sprite0.png')
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.velocity = 5
def point_at(self, x, y):
direction = pygame.math.Vector2(x, y) - self.rect.center
angle = direction.angle_to((0, -1))
self.image = pygame.transform.rotate(self.original_image, angle)
self.rect = self.image.get_rect(center=self.rect.center)
def move(self, x, y):
self.rect.move_ip(x * self.velocity, y * self.velocity)
player = Player(200, 200)
all_sprites = pygame.sprite.Group(player)
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
player.point_at(*pygame.mouse.get_pos())
keys = pygame.key.get_pressed()
player.move(keys[pygame.K_d]-keys[pygame.K_a], keys[pygame.K_s]-keys[pygame.K_w])
wn.fill((255, 255, 255))
all_sprites.draw(wn)
pygame.display.update()
마우스 방향으로 개체를 이동하려면 유형 의 direction
및 position
속성 을 추가해야 합니다 pygame.math.Vecotr2. 방향은에서 변경되고 point_at
위치는 move
방향에 따라에서 변경됩니다 . rect
속성을 업데이트 할 수 있습니다.
최소한의 예 :

import pygame
wn = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.original_image = pygame.image.load('Sprite0.png')
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.direction = pygame.math.Vector2((0, -1))
self.velocity = 5
self.position = pygame.math.Vector2(x, y)
def point_at(self, x, y):
self.direction = pygame.math.Vector2(x, y) - self.rect.center
if self.direction.length() > 0:
self.direction = self.direction.normalize()
angle = self.direction.angle_to((0, -1))
self.image = pygame.transform.rotate(self.original_image, angle)
self.rect = self.image.get_rect(center=self.rect.center)
def move(self, x, y):
self.position -= self.direction * y * self.velocity
self.position += pygame.math.Vector2(-self.direction.y, self.direction.x) * x * self.velocity
self.rect.center = round(self.position.x), round(self.position.y)
player = Player(200, 200)
all_sprites = pygame.sprite.Group(player)
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.MOUSEMOTION:
player.point_at(*event.pos)
keys = pygame.key.get_pressed()
player.move(keys[pygame.K_d]-keys[pygame.K_a], keys[pygame.K_s]-keys[pygame.K_w])
wn.fill((255, 255, 255))
all_sprites.draw(wn)
pygame.display.update()
elif event.type == pygame.MOUSEMOTION:
블록을 제거하고 루프에 player.point_at(*pygame.mouse.get_pos())
직접 넣으십시오 while
.
스프라이트가 화면 밖으로 압축되지 않도록 시계를 만듭니다.
마지막으로
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
player.rect.y -= 1
if keys[pygame.K_s]:
player.rect.y += 1
if keys[pygame.K_a]:
player.rect.x -= 1
if keys[pygame.K_d]:
player.rect.x += 1
플레이어를 제어합니다.
예:
import pygame
from math import atan2, degrees
wn = pygame.display.set_mode((400, 400))
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 40), pygame.SRCALPHA)
self.image.fill((255, 0, 0))
self.rect = self.image.get_rect(topleft=(185, 180))
def point_at(self, x, y):
rotated_image = pygame.transform.rotate(self.image, degrees(atan2(x-self.rect.x, y-self.rect.y)))
new_rect = rotated_image.get_rect(center=self.rect.center)
wn.fill((0, 0, 0))
wn.blit(rotated_image, new_rect.topleft)
player = Player()
clock = pygame.time.Clock() # Create the clock
while True:
clock.tick(30) # Use the clock
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keys = pygame.key.get_pressed() # Get al the pressed keys
if keys[pygame.K_w]:
player.rect.y -= 1
if keys[pygame.K_s]:
player.rect.y += 1
if keys[pygame.K_a]:
player.rect.x -= 1
if keys[pygame.K_d]:
player.rect.x += 1
player.point_at(*pygame.mouse.get_pos()) # Put this here
pygame.display.update()
산출:
