我欢迎大家!我开始学习 pygame,对于我的游戏,有必要为角色制作一个附加的相机,我做到了,但现在我的代码已经有点困惑了。一般来说,你需要制作一个角色的空闲动画,我做了几次尝试,但不知何故没有成功。请告知如何做到这一点。提前致谢。这是我的代码:
import sys
from random import randint
class Enemies(pygame.sprite.Sprite):
def __init__(self, pos, group):
super(Enemies, self).__init__(group)
self.image = pygame.image.load('enemy/name.png')
self.rect = self.image.get_rect(topleft = pos)
class Player(pygame.sprite.Sprite):
def __init__(self, pos, group):
super(Player, self).__init__(group)
self.idle_animation = [pygame.image.load('player/idle/idle' + f"{i}.png") for i in range(1, 11)]
self.idle = True
self.image = pygame.image.load('player/idle/idle1.png')
self.rect = self.image.get_rect(center = pos)
self.direction = pygame.math.Vector2()
self.speed = 5
def input(self):
key = pygame.key.get_pressed()
if key[pygame.K_w]:
self.direction.y = -1
self.idle = False
elif key[pygame.K_s]:
self.direction.y = 1
self.idle = False
else:
self.direction.y = 0
self.idle = True
if key[pygame.K_d]:
self.direction.x = 1
self.idle = False
elif key[pygame.K_a]:
self.direction.x = -1
self.idle = False
else:
self.direction.x = 0
self.idle = True
if self.idle == True:
for i in range(1, 11):
self.image = pygame.image.load('player/idle/idle' + str(i) + '.png')
def update(self):
self.input()
self.rect.center += self.direction * self.speed
class CameraGroup(pygame.sprite.Group):
def __init__(self):
super(CameraGroup, self).__init__()
self.display_surface = pygame.display.get_surface()
self.offset = pygame.math.Vector2()
self.half_w = self.display_surface.get_size()[0] // 2
self.half_h = self.display_surface.get_size()[1] // 2
self.ground_surf = pygame.image.load('bg/bg.png')
self.ground_rect = self.ground_surf.get_rect(topleft = (0,0))
def center_target_camera(self, target):
self.offset.x = target.rect.centerx - self.half_w
self.offset.y = target.rect.centery - self.half_h
def custom_draw(self, player):
self.center_target_camera(player)
ground_offset = self.ground_rect.topleft - self.offset
self.display_surface.blit(self.ground_surf, ground_offset)
for sprite in sorted(self.sprites(), key = lambda sprite: sprite.rect.centery):
offset_pos = sprite.rect.topleft - self.offset
self.display_surface.blit(sprite.image, offset_pos)
pygame.init()
screen = pygame.display.set_mode((640, 360), pygame.FULLSCREEN)
pygame.mouse.set_visible(False)
camera_group = CameraGroup()
player = Player((640, 360), camera_group)
for i in range(20):
random_x = randint(0, 1000)
random_y = randint(0, 1000)
Enemies((random_x, random_y), camera_group)
fps = 30
clock = pygame.time.Clock()
true = True
while true:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if pygame.key.get_pressed()[pygame.K_ESCAPE]:
event.type = pygame.QUIT
screen.fill([255, 255, 255])
camera_group.update()
camera_group.custom_draw(player)
pygame.display.flip()