【问题标题】:How do I move an object towards the mouse without having the mouse position affect speed in Pygame? [duplicate]如何在不让鼠标位置影响 Pygame 中的速度的情况下将对象移向鼠标? [复制]
【发布时间】:2021-10-02 07:25:28
【问题描述】:

所以我试图在 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 中规范化向量?

【问题讨论】:

标签: python python-3.x vector pygame normalize


【解决方案1】:

如果非要积分的话

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

【讨论】:

    猜你喜欢
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多