What Is A Good Way To Layer Like This In Pygame?
I've been working on a small project in pygame. It's an overhead 2D game, but if a player is behind an object, I need the player to be one layer behind it. If the player is in fron
Solution 1:
Stop working with Surfaces
directly. Use the pygame's Sprite
class.
Then you can simply give your Sprites a _layer
attribute and use a LayeredUpdates
group for managing them, and the group will take care of the order of blitting.
Here's an example:
import pygame
pygame.init()
screen = pygame.display.set_mode((300, 300))
classActor(pygame.sprite.Sprite):
def__init__(self, group, color, layer, pos):
self.image = pygame.Surface((30, 30))
self.image.fill(color)
self.rect = self.image.get_rect(center=pos)
self._layer = layer
pygame.sprite.Sprite.__init__(self, group)
group = pygame.sprite.LayeredUpdates()
Actor(group, (255, 255, 255), 0, (100, 100))
Actor(group, (255, 0, 255), 1, (110, 110))
Actor(group, (0, 255, 255), 0, (120, 120))
Actor(group, (255, 255, 0), 3, (130, 130))
Actor(group, (0, 0, 255), 2, (140, 140))
run = Truewhile run:
for e in pygame.event.get():
if e.type ==pygame.QUIT:
run = False
screen.fill((0,0,0))
group.update()
group.draw(screen)
pygame.display.flip()
Note how the order of the sprites is determined by the value of the _layer
attribute.
Solution 2:
I tried with this code (it most likely works)
When the red surface is behind the green the green will overlap, that's why I've kept it a little transparent. When the red overtakes it will be blitted on the green. The code is same as you did. IDK why yours doesn't work
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800,600))
surface1 = pygame.Surface((50,50))
surface1.fill((255,0,0))
surface2 = pygame.Surface((50,50))
surface2.fill((0,255,0))
surface2.set_alpha(196)
surface1X = 0
surface1Y = 275
surface2X = 400
surface2Y = 275
x_change = 0
y_change = 0
speed = 2whileTrue:
foreventin pygame.event.get():
ifevent.type == pygame.QUIT:
pygame.quit()
quit()
ifevent.type == pygame.KEYDOWN:
ifevent.key == pygame.K_LEFT:
x_change = -speed
ifevent.key == pygame.K_RIGHT:
x_change = speed
ifevent.key == pygame.K_UP:
y_change = -speed
ifevent.key == pygame.K_DOWN:
y_change = speed
ifevent.type == pygame.KEYUP:
ifevent.key == pygame.K_LEFT orevent.key == pygame.K_RIGHT orevent.key == pygame.K_UP orevent.key == pygame.K_DOWN:
x_change = 0
y_change = 0
surface1X += x_change
surface1Y += y_change
screen.fill((255,255,255))
if (surface1X < surface2X):
screen.blit(surface1, (surface1X, surface1Y))
screen.blit(surface2, (surface2X, surface2Y))
else:
screen.blit(surface2, (surface2X, surface2Y))
screen.blit(surface1, (surface1X, surface1Y))
pygame.display.update()
clock.tick(60)
Post a Comment for "What Is A Good Way To Layer Like This In Pygame?"