如何向鼠标方向旋转精灵并移动它?

How do I rotate a sprite towards the mouse and move it?

我很困惑,在我的代码中,精灵的坐标似乎没有改变它所在的位置。输入 (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()

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

输出:

请仔细阅读的答案。角度的计算

degrees(atan2(x-self.rect.x, y-self.rect.y))

工作偶然。它有效,因为 atan2(x, y) == atan2(-y, x)-pi/2.

矢量(xy)的角度为atan2(y, x)。 y轴需要反转(-y)因为y轴一般是向上的,但是在PyGame坐标系中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))

另见


Sprite 绘制在 rect 属性中存储的位置。您根本不需要 xy 属性。只需设置矩形的位置 (rect)。
向构造函数添加 xy 参数:

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改变精灵的位置:

class Player(pygame.sprite.Sprite):
    # [...]

    def move(self, x, y):
        self.rect.move_ip(x, y)

调用move,当你想改变Sprite的位置时:

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

A Sprite 应始终包含在 pygame.sprite.Group. See pygame.sprite.Group.draw():

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.

添加一个Group并将Sprite添加到Group:

player = Player(200, 200)
all_sprites = pygame.sprite.Group(player)

当你想绘制Group中的所有Sprites时调用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)

    # [...]

最小示例: repl.it/@Rabbid76/PyGame-SpriteRotateToMouse

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

如果你想在鼠标的方向移动对象,那么你必须添加 directionposition 类型的 pygame.math.Vecotr2 属性。方向在 point_at 中改变,位置在 move 中改变,具体取决于方向。 rect 属性必须更新。


最小示例: repl.it/@Rabbid76/PyGame-SpriteFollowMouse

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