Lucky38i Lucky38i - 25 days ago 7
Python Question

Pygame | blited image keeps jumping all over the place

Hi guys I was wondering if I could get a bit of help with this. I'm learning Classes in python and trying to incorporate it into my current project for uni.

So below is the code for the class as-well as some variables used by it

class Asteroid():
def __init__(self, char, startX, startY):
self.char = char
self.startX = startX
self.startY = startY
self.drawChar()

def drawChar (self):
self.space = pygame.image.load (self.char)
self.space = self.space.convert_alpha()
gameDisplay.blit(self.space,
(random.randint(0,display_width),
random.randint(0,display_height)))


Basically this class incorporates all the data I need to load in 'Asteroids'.

below is part of the main code where the class is actually being used:

Asteroid(random.choice(asteroid),200,300 )


Also below is the code for the variable
asteroid
:

asteroid = [
'Sprites/Asteroid1.png',
'Sprites/Asteroid2.png',
'Sprites/Asteroid3.png']


So the actual problem that occurs is when I run the code the asteroids are blited unto the surface but they're jumping all over the place. Not only that but different asteroids are being blited rather than one chosen asteroid. Why is this occuring?

On a side note the asteroid also have a white background, I tried converting them but that doesn't help.

Answer

Because you tell it to. The code

gameDisplay.blit(self.space,
            (random.randint(0,display_width),
             random.randint(0,display_height)))

literally says "blit the image onto the display at a random location." Specifically, random.randint(0,...) picks random positions from zero to the screen size.

Keep in mind that this display code gets called every time the screen needs to be updated, not just when you start the game. To display at static coordinates, make the coordinates static:

gameDisplay.blit(self.space, (self.startX, self.startY))