Pergunta

Whenever I try to add 0.01 to my x position, nothing happens, but when I add -0.01 it works fine.

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

Obviously, having the two there at the same time would make the sprite not move at all, but it still moves to the left.

Foi útil?

Solução

Pygame Rects use integers for these attributes, because they represent pixel values, which is the smallest unit possible on the screen.

So, firstly, incrementing by 0.01 is pointless. Secondly, you are falling victim to int rounding which is why currently decrementing is working while incrementing isn't. This is because (2 + 0.01) 2.01 becomes 2, where as 1.99 becomes 1. i.e. successful decrementing.

This is easily shown using the 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

My recommendation for the future, is to store position in a tuple (x,y) where x and y are floats. With this you can increment with 0.01 and it will have effect. But then convert these to int when setting the rect attributes i.e.

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)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top