Oct-25-2023, 08:09 PM
(Oct-25-2023, 04:25 AM)menator01 Wrote: Taking the following snippet, is it possible to create a pygame.Rect() and add it to a sprite group?
Been looking for awhile and not really found anything. Maybe just tired. lol.
In the following example, I can get func1 to display but, not sure how to add func2 to a sprites group.
Any help would be great.
import pygame import sys # Initiate pygame pygame.init() # Create some settings size = (1280, 720) screen = pygame.display.set_mode(size) pygame.display.set_caption('Shmup') clock = pygame.time.Clock() hud = pygame.sprite.Group() def func1(): arect = pygame.Rect(30,10,125,25) pygame.draw.rect(screen, 'green', arect) def func2(): arect = pygame.Rect(30, 35, 125, 25) hud.add(arect) while True: event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit() hud.update() hud.draw(screen) func1() pygame.display.update() clock.tick(60) pygame.quit()
pygame.sprite.Group only except sprites.
sprite = pygame.sprite.Sprite() # Sprite must have image and a rect variable. sprite.rect = pygame.Rect(30, 35, 125, 25) sprite.image = pygame.Surface(sprite.rect.size) sprite.image.fill('green') hud.add(sprite)When you learn classes.
class MySprite(pygame.sprite.Sprite): def __init__(self, color, x, y, w, h): super().__init__() self.rect = pygame.Rect(x, y, w, h) self.image = pygame.Surface(self.rect.size) self.image.fill(color) hud.add(MySprite('green', 30, 35, 125, 25))
99 percent of computer problems exists between chair and keyboard.