Skip to main content
 首页 » 编程设计

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

2025年05月04日9jpfss

每当我尝试将 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)