如何在不让鼠标位置影响 Pygame 中的速度的情况下将对象移向鼠标?

问题描述

所以我试图在 Pygame 中测试一个简单的战斗系统,玩家基本上可以根据鼠标位置向某个区域发射弹丸。例如,当他点击屏幕左上角时,弹丸会以稳定的速度向那里移动。我创建了一个函数来移动列表中的每个项目符号,这是函数

def move_bullet(bullet_pos,direction):
    # Todo Make the speed of the bullet the same no matter which direction it's being fired at

    bullet_pos[0] += direction[0]/50
    bullet_pos[1] += direction[1]/50

    bullet_rect = pygame.Rect((bullet_pos[0],bullet_pos[1]),BULLET_SIZE)
    return bullet_rect

当mousebuttondown事件触发时,玩家的矢量位置减去鼠标的矢量位置,计算出方向。

然而,我注意到我越接近子弹的玩家/原点,子弹走得越慢,因为方向向量更小,所以速度会根据鼠标的位置而有所不同。我听说过向量归一化,但我不知道如何实现它,因为在做了一些研究之后,显然你通过获取它的大小并将 X 和 Y 值除以大小来归一化向量?我从可汗学院得到它,但它实际上不起作用。我正在为此纠结,所以我别无选择,只能在这里问这个问题。

TL;博士

如何在 Pygame 中规范化向量?

解决方法

如果一定要加分

x1 = 10
y1 = 10

x2 = 100
y2 = 500

然后你可以计算距离并使用pygame.math.Vector2

import pygame

dx = x2-x1
dy = y2-y1

distance = pygame.math.Vector2(dx,dy)

v1 = pygame.math.Vector2(x1,y1)
v2 = pygame.math.Vector2(x2,y2)

distance = v2 - v1

然后你可以标准化它

direction = distance.normalize()

它应该总是给出距离1

print('distance:',direction[0]**2 + direction[1]**2)  # 0.999999999999
# or
print('distance:',direction.length() )

然后使用 speed

移动对象
pos[0] += direction[0] * speed
pos[1] += direction[1] * speed

编辑:

如果您将使用 Rect

SIZE = (10,10)
bullet_rect = pygame.Rect((0,0),SIZE)
bullet_rect.center = (x1,y1)

那么你也可以计算

distance = v2 - bullet_rect.center

direction = distance.normalize()

并用一行移动它

bullet_rect.center += direction * speed

Rect 有很多有用的函数。但有一个减号 - 它保持位置为 integers 所以它舍入浮点值,有时它会产生奇怪的移动或每移动几下丢失一个像素。


文档:PyGame.math