Apr-08-2024, 06:52 PM
Hi,
thank you for answering...
I think, I got it now...
Because there were problems, if
I put it in a own function "move()".
Now it works...
thank you for answering...
I think, I got it now...
Because there were problems, if
self.rect.centerx = max(self.xmin, min(self.xmax, xpos))is inside the function "spaceship.update()"
I put it in a own function "move()".
Now it works...
#create spaceship class class Spaceship(pygame.sprite.Sprite): def __init__(self, x, y, health): pygame.sprite.Sprite.__init__(self) self.x = x self.y = y self.health_start = health self.health_remaining = health self.image = pygame.image.load("images/ship.png") self.rect = self.image.get_rect() self.rect.center = [x, y] self.xmin = self.rect.width // 2 # Compute Spaceship x range. self.xmax = screen_width - self.xmin self.last_shot = pygame.time.get_ticks() def move(self, xpos): self.rect.centerx = max(self.xmin, min(self.xmax, xpos)) def update(self): #set a cooldown variable cooldown = 500 #milliseconds game_over = 0 #record current time time_now = pygame.time.get_ticks() #shoot, get key press key = pygame.key.get_pressed() if key[pygame.K_SPACE] and time_now - self.last_shot > cooldown: #laser_fx.play() bullet_1 = Bullets(self.rect.centerx - 43, self.rect.top) bullet_2 = Bullets(self.rect.centerx + 43, self.rect.top) #bullet = Bullets(self.rect.centerx, self.rect.top) bullet_group.add(bullet_1) bullet_group.add(bullet_2) self.last_shot = time_now #update mask self.mask = pygame.mask.from_surface(self.image) #draw health bar pygame.draw.rect(screen, red, (self.rect.x, (self.rect.bottom + 10), self.rect.width, 15)) if self.health_remaining > 0: pygame.draw.rect(screen, green, (self.rect.x, (self.rect.bottom + 10), int(self.rect.width * (self.health_remaining / self.health_start)), 15)) elif self.health_remaining <= 0: explosion = Explosion(self.rect.centerx, self.rect.centery, 3) explosion_group.add(explosion) self.kill() game_over = -1 return game_over