在斜边上移动很可能需要您的对象在y轴或x轴每帧移动不到一个像素,由于
rects
只能容纳整数,因此您需要一个新属性
position
,其中包含精灵的浮点精度位置。您可以使用
pygame.math.Vector2
创建具有实用方法的向量,例如
normalize()
和向其他向量添加、减去、乘以等。
假设您已经创建了一个属性self.position = pygame.math.Vector2(0, 0)
(或任何您想要它开始的位置),您可以像这样操作:
def hunt_player(self, player):
player_position = pygame.math.Vector2(player.rect.topleft)
direction = player_position - self.position
velocity = direction.normalize() * self.speed
self.position += velocity
self.rect.topleft = self.position
通过将玩家的位置减去敌人的位置,您将获得一个指向玩家的向量。如果我们将方向向量添加到我们的位置,我们将立即传送到玩家。相反,我们规范化向量(使其长度为1像素),并乘以我们的速度属性。新创建的向量将是一个指向玩家的向量,其长度为我们的速度。
完整示例
import pygame
pygame.init()
SIZE = WIDTH, HEIGHT = 720, 480
FPS = 60
BACKGROUND_COLOR = pygame.Color('white')
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
class Hunter(pygame.sprite.Sprite):
def __init__(self, position):
super(Hunter, self).__init__()
self.image = pygame.Surface((32, 32))
self.image.fill(pygame.Color('red'))
self.rect = self.image.get_rect(topleft=position)
self.position = pygame.math.Vector2(position)
self.speed = 2
def hunt_player(self, player):
player_position = player.rect.topleft
direction = player_position - self.position
velocity = direction.normalize() * self.speed
self.position += velocity
self.rect.topleft = self.position
def update(self, player):
self.hunt_player(player)
class Player(pygame.sprite.Sprite):
def __init__(self, position):
super(Player, self).__init__()
self.image = pygame.Surface((32, 32))
self.image.fill(pygame.Color('blue'))
self.rect = self.image.get_rect(topleft=position)
self.position = pygame.math.Vector2(position)
self.velocity = pygame.math.Vector2(0, 0)
self.speed = 3
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.velocity.x = -self.speed
elif keys[pygame.K_RIGHT]:
self.velocity.x = self.speed
else:
self.velocity.x = 0
if keys[pygame.K_UP]:
self.velocity.y = -self.speed
elif keys[pygame.K_DOWN]:
self.velocity.y = self.speed
else:
self.velocity.y = 0
self.position += self.velocity
self.rect.topleft = self.position
player = Player(position=(350, 220))
monster = Hunter(position=(680, 400))
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
player.update()
monster.update(player)
screen.fill(BACKGROUND_COLOR)
screen.blit(player.image, player.rect)
screen.blit(monster.image, monster.rect)
pygame.display.update()
结果
![这是一张图片,请点击链接查看](https://istack.dev59.com/bef2Y.gif)
这是一张图片,请点击链接查看。