'Pygame draw multiple/duplicate sprites same class
The Problem: I want to add the exact same Sprite (it's a 25x25 white box) behind another one
the Sprite starts off at x,y 300,300 I have key functions that allow the Sprite to move in any direction
Let's say, that I move my Sprite to x,y 150,210... how do I grab that NEW position of that original Sprite, and then draw a copy of that Sprite directly "behind" that Sprites new position of x,y 150,210?
The end result is:
- there are TWO 25x25 squares together.
- On keypress, the two squares should always stay together. The "TWO" could be 10 or 20 or 40 squares at any point
- I do not want to increase the height of the sprite as a solution, I explicitly want a copy of the sprite
Please let me know if this question requires better context etc. Thanks in advance
Minimal reproducible example
import pygame
from random import randint
from sys import exit
pygame.init()
game_active = True
clock = pygame.time.Clock() #an object to track time
def display_surface():
disp_surface = pygame.display.set_mode(size = (610, 700))
return disp_surface
disp_surface = display_surface()
class square(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
image1 = pygame.image.load("square1.png").convert_alpha()
x_pos = 300
y_pos = 300
self.image = image1
self.rect = self.image.get_rect(x = x_pos,y = y_pos)
squaregroup = pygame.sprite.GroupSingle()
squaregroup.add(square())
while True:
for eachevent in pygame.event.get():
if eachevent.type == pygame.QUIT:
pygame.quit()
exit()
if eachevent.type == pygame.KEYDOWN and eachevent.key == pygame.K_SPACE:
game_active = True
keys = pygame.key.get_pressed()
events = pygame.event.get()
left = keys[pygame.K_LEFT]
right = keys[pygame.K_RIGHT]
up = keys[pygame.K_UP]
down = keys[pygame.K_DOWN]
if left:
squaregroup.sprite.rect.x -= 1
if right:
squaregroup.sprite.rect.x += 1
if up:
squaregroup.sprite.rect.y -= 1
if down:
squaregroup.sprite.rect.y += 1
if game_active:
disp_surface = display_surface()
squaregroup.draw(disp_surface)
else:
disp_surface.fill((64,64,64))
pygame.display.update()
clock.tick(60)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
