Желая добавить след в спрайт Pygame - PullRequest
0 голосов
/ 11 марта 2020

Я пытаюсь создать простую игру Snake, которая сама оставляет за собой след.

Я попытался проверить pygame.display.update и alphasurf, но все, что я хочу, это прямоугольник, чтобы оставить простое след за собой.

Почти как если бы он сам создавал дубликаты при движении.

Я также не могу просто удалить screen.fill, потому что хочу добавить и другие движущиеся части

1 Ответ

0 голосов
/ 11 марта 2020

Согласно this , один из способов сделать это - создать прозрачную поверхность размером с экран, на который вы будете бликать объекты с помощью следов. Это должна быть альфа-поверхность на пиксель, которую вы можете создать, передав специальный флаг pygame.SRCALPHA. Разбейте объекты и уменьшите альфа всех пикселей на alpha_surf каждого кадра, заполнив его прозрачным белым цветом, а также пропустите флаг pygame.BLEND_RGBA_MULT, чтобы затрагивать только альфа-канал.
Примером может быть:

import pygame as pg
from pygame.math import Vector2
class Player(pg.sprite.Sprite):
def __init__(self, pos, *groups):
super().__init__(*groups)
self.image = pg.Surface((50, 50), pg.SRCALPHA)
pg.draw.circle(self.image, pg.Color('dodgerblue'), (25, 25), 25)
self.rect = self.image.get_rect(center=pos)
self.vel = Vector2(0, 0)
self.pos = Vector2(pos)
def update(self):
self.pos += self.vel
self.rect.center = self.pos
def main():
pg.init()
screen = pg.display.set_mode((640, 480))
# Blit objects with trails onto this surface instead of the screen.
alpha_surf = pg.Surface(screen.get_size(), pg.SRCALPHA)
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
player = Player((150, 150), all_sprites)
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
elif event.type == pg.KEYDOWN:
if event.key == pg.K_d:
player.vel.x = 5
elif event.key == pg.K_a:
player.vel.x = -5
elif event.key == pg.K_w:
player.vel.y = -5
elif event.key == pg.K_s:
player.vel.y = 5
elif event.type == pg.KEYUP:
if event.key == pg.K_d and player.vel.x > 0:
player.vel.x = 0
elif event.key == pg.K_a and player.vel.x < 0:
player.vel.x = 0
elif event.key == pg.K_w:
player.vel.y = 0
elif event.key == pg.K_s:
player.vel.y = 0
# Reduce the alpha of all pixels on this surface each frame.
# Control the fade speed with the alpha value.
alpha_surf.fill((255, 255, 255, 220), special_flags=pg.BLEND_RGBA_MULT)
all_sprites.update()
screen.fill((20, 50, 80)) # Clear the screen.
all_sprites.draw(alpha_surf) # Draw the objects onto the alpha_surf.
screen.blit(alpha_surf, (0, 0)) # Blit the alpha_surf onto the screen.
pg.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
pg.quit()

Приветствия.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...