Victor Chao
Victor Chao

Reputation: 1

pygame sprite not moving automatically with each sprite update

I'm trying to make a cut scene for a pygame that I'm building, and in this pygame I'm trying to get the main player sprite to spawn at the rightmost side of the screen, before slowly moving towards the center. For some reason, rather than moving, it just stays completely still, despite the fact that the same logics that I applied in the cutscene works completely fine in the main game when I'm using keypresses to move the player instead of an automatic update.

I basically just followed the same logic that I did in my main game except instead of moving as a result of a keypress, it moves as a result of a sprite update. This is my code for the sprite:

class Player(pygame.sprite.Sprite):
  def __init__(self):
      pygame.sprite.Sprite.__init__(self)
      self.image = pygame.Surface((30, 60))
      self.image = pygame.image.load("soldier.png").convert_alpha()
      self.rect = self.image.get_rect()
      self.rect.x = WIDTH - 30
      self.rect.y = HEIGHT - 60
      self.speedx = -5
      self.speedy = 0
      self.count = 0
      tru = False
  def update(self):
      self.count += 1
      if self.count > 10:
          self.speedx -= 5
          self.count = 0
      else:
          self.speedx = 0
          if self.rect.x < WIDTH / 2:
              self.speedx = 0
      self.rect.x += self.speedx

And here is my main game loop

game_over = True
running = True
CurrentLevel = 1
while running:
    all_sprites = pygame.sprite.Group()
    curtime = pygame.time.get_ticks()
    platforms = pygame.sprite.Group()
    bullets = pygame.sprite.Group()
    grounds = pygame.sprite.Group()
    thentime = pygame.time.get_ticks()
    for plat in PLATFORMS:
        p = Platform(*plat)
        all_sprites.add(p)
        platforms.add(p)
    for gro in GROUNDS:
        g = Ground(*gro)
        all_sprites.add(g)
        grounds.add(g)
    player = Player()
    all_sprites.add(player)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_d:
                running = False
    all_sprites.update()

    screen.fill(WHITE)
    screen.blit(bg, [0, 0])
    all_sprites.draw(screen)
    pygame.display.flip()     

This is what the outcome becomes: Output That player sprite at the far right side of the screen just remains there and doesn't move like it should. Does anyone know whats going on?

Upvotes: 0

Views: 193

Answers (1)

Calvin Godfrey
Calvin Godfrey

Reputation: 2369

Inside your while running loop, you have the line player = Player() and all_sprites.add(player). That means that each frame, your game is creating a new player object and instantiating it on the right side of the screen, so it never has a chance to move.

Upvotes: 0

Related Questions