python - 对角运动

标签 python pygame

我正在尝试实现一个追逐玩家的敌人,但是当敌人沿对角线移动时,它的移动速度似乎比在单轴上移动时慢,我不确定为什么。这是我的敌人代码:

import pygame
import constants
import math
from Character import Player

class Enemy(pygame.sprite.Sprite):

    def __init__(self, filename, x, y):

        super().__init__()    

        self.image = pygame.image.load(filename).convert()
        self.image.set_colorkey(constants.BLACK)

        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x

        self.speedx = -3
        self.speedy = -3

        self.health = 100

    def update(self, player):

        dx = self.rect.x - player.rect.x
        dy = self.rect.y - player.rect.y

        dist = math.hypot(dx, dy)

        dx = dx / dist
        dy = dy / dist

        self.rect.x += dx * self.speedx
        self.rect.y += dy * self.speedy




* in the main loop *

current_room.enemy_sprites.update(player)

让我知道是否需要更多代码,但我认为不会有,因为我的其他代码都不会影响敌人的移动。任何帮助都将不胜感激!

最佳答案

当你水平或垂直移动时,你的速度是-3,当你沿对角线移动时,你的速度变成-3/1.41(让我们考虑dx == dy),并且由于四舍五入,它变成了 2,大约慢了 1.5 倍。

关于python - 对角运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51810381/

相关文章:

python - os.read() 给出 OSError : [Errno 22] Invalid argument when reading large data

Python for循环,打印相同的项目一次

python - 如何在 Pygame 中添加文本语音

python - 使用 python 压缩所有子目录

python - 如何停止字典洗牌? (Python)

Python属性错误: module 'string' has no attribute 'maketrans'

python - Pygame:赋值解包抛出 SystemError

python - 在pygame中制作图像 "fit to screen"?

python - 我正在尝试制作一个基于 "top down"图 block 的游戏。我不知道如何最初制作瓦片 map 来放置图像

python - 程序中的奇怪错误,某些对象在使用后出现 "turns off"