我可以将精灵的x位置增加-0.01,但不能增加0.01



每当我试图在x位置加0.01时,什么都不会发生,但当我加-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

很明显,将两者同时存在会使精灵根本不移动,但它仍然会向左移动。

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

因此,首先,增加0.01是毫无意义的。其次,您是整数舍入的受害者,这就是为什么当前递减有效,而递增无效。这是因为(2+0.01)2.01变为2,其中as 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

我对未来的建议是,将位置存储在元组(x,y)中,其中x和y是浮点值。有了这个,你可以增加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)

相关内容

最新更新