python - 我可以将 Sprite 的 x 位置增加 -0.01,但不是 0.01?

标签 python pygame sprite

每当我尝试将 0.01 添加到我的 x 位置时,没有任何反应,但当我添加 -0.01 时它工作正常。

class Ball(Sprite):
    def __init__(self,colour,x,y,radius,thickness):
        self.speed = 0.01
        self.angle = math.pi/2

        self.colour = colour

        self.x = x
        self.y = y
        self.radius = radius
        self.thickness = thickness

        self.rect = pygame.Rect(self.x,self.y,self.radius*2,self.radius*2)

    def draw(self,screen):
        pygame.draw.circle(screen,self.colour,[self.rect.x,self.rect.y],self.radius,self.thickness)

    def move(self):
        self.rect.x += 0.01 # this doesn't work
        self.rect.x -= 0.01 # this does

很明显,如果两者同时存在, Sprite 根本不会移动,但它仍然会向左移动。

最佳答案

Pygame Rects 对这些属性使用整数,因为它们表示像素值,这是屏幕上可能的最小单位。

所以,首先,增加 0.01 是没有意义的。 其次,您正在成为 int 舍入的受害者,这就是为什么当前递减有效而递增无效的原因。这是因为 (2 + 0.01) 2.01 变为 2,其中 1.99 变为 1。即成功递减。

这很容易使用 python shell 显示

>>> rect = pygame.Rect(100, 100, 10, 10)
>>> rect
<rect(100, 100, 10, 10)>
>>> rect.x
100
>>> rect.x += 0.01
>>> rect.x
100
>>> rect.x -= 0.01
>>> rect.x
99

我对 future 的建议是将位置存储在元组 (x,y) 中,其中 x 和 y 是 float 。有了这个你可以增加 0.01 并且它会生效。 但是在设置 rect 属性时将它们转换为 int ,即

pos = (x, y)
x = pos[0]
x += 0.01 ## or anything you want
pos = (x, y)
## got to unpack and repack due to immutability of tuples (there are other ways)
rect.x = int(x)

关于python - 我可以将 Sprite 的 x 位置增加 -0.01,但不是 0.01?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23350574/

相关文章:

python - 在 fedora 上运行 ansible 返回下面的错误,这迫使我自己安装 python

python - 如何根据来自 for 循环的值创建多维列表

python - 如何在一个函数中休眠而不休眠整个程序

c# - 将所有图像缩放至控制台尺寸 XNA

SpriteKit 如何添加激光束并在碰撞点调整其大小

python - 如何阻止 Google Cloud SQL 中的 SQL 注入(inject)?

python - 从 PyCharm 中的脚本加载环境变量

python - 在 pygame 中我遇到这个问题 : unsupported operand type(s) for +=: 'int' and 'list'

python - Pygame 全屏放大

html - 在不调用 CSS 中的图像 url 的情况下在 Sprite 图像之间淡入淡出