使用Pygame和Python实现跟随玩家的相机
我有50个外星人角色想要跟着玩家走,但首先我想让摄像机跟着玩家,无论他走到哪里。
我之前在一个旧游戏里实现过这个功能,不过那时候我没有使用类和精灵组,所以效率不高。
在这个游戏里,我把玩家放在屏幕的中心,其他的东西都在动。为此,我设置了两个变量,叫做 CameraX
和 CameraY
,当玩家移动的时候,这两个摄像机的变量就会上下变化。但是,在我的脚本里,外星人并没有更新位置。总之,这里是我的脚本:
import pygame, random, sys
from pygame.locals import *
pygame.init()
black = ( 0, 0, 0)
white = ( 255, 255, 255)
red = ( 255, 0, 0)
screen_width = 1080
screen_height = 720
screen = pygame.display.set_mode([screen_width,screen_height])
alien_list = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
Alien = "graphics\sprites\Alien.png"
Player = "graphics\sprites\Player.png"
CameraX = 0
CameraY = 0
def main():
class Enemy(pygame.sprite.Sprite):
def __init__(self, image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image).convert_alpha()
self.rect = self.image.get_rect()
def Create():
for i in range(50):
alien = Enemy(Alien)
alien.rect.x = random.randrange(screen_width - 50 - CameraX)
alien.rect.y = random.randrange(screen_height - 50 - CameraY)
alien_list.add(alien)
all_sprites.add(alien)
player = Enemy(Player)
all_sprites.add(player)
done = False
clock = pygame.time.Clock()
score = 0
moveCameraX = 0
moveCameraY = 0
player.rect.x = 476
player.rect.y = 296
Enemy.Create()
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == KEYDOWN:
if event.key == K_w:
moveCameraY = -10
if event.key == K_s:
moveCameraY = 10
if event.key == K_a:
moveCameraX = -10
if event.key == K_d:
moveCameraX = 10
if event.type == KEYUP:
if event.key == K_w:
moveCameraY = 0
if event.key == K_s:
moveCameraY = 0
if event.key == K_a:
moveCameraX = 0
if event.key == K_d:
moveCameraX = 0
screen.fill(white)
enemys_hit = pygame.sprite.spritecollide(player, alien_list, True)
for enemy in enemys_hit:
score += 1
print(score)
all_sprites.draw(screen)
clock.tick(40)
pygame.display.flip()
pygame.quit()
然后是运行整个程序的脚本:
import pygame
import GameEg
from pygame.locals import *
pygame.init()
game = GameEg.main()
game.main()
谢谢你的时间和帮助。
2 个回答
0
关于相机的部分: 我认为最简单的相机实现方式就是用一个相机的x偏移量和y偏移量。如果一个精灵在位置x,y,那么它应该在位置x+x偏移量,y+y偏移量被绘制出来。
现在,如果我们想让玩家在位置player_x,player_y处位于屏幕的中心,每次更新时可以这样做:
我们正常更新玩家的位置。
然后我们设置x偏移量和y偏移量为: x偏移量 = 屏幕宽度/2 - player_x y偏移量 = 屏幕高度/2 - player_y
接着我们绘制所有的精灵(包括玩家) 在位置sprite_x + x偏移量, sprite_y + y偏移量。
重复这个过程就可以了。希望这对你有帮助:)
1
你不需要用 CameraX
和 CameraY
这两个变量。相反,当你接收到键盘输入时,只需要让所有的外星人朝那个方向移动就行了。而且,你现在的代码里没有任何实际让玩家和外星人移动的部分。你需要在你的类里添加一个更新函数,用来改变源矩形的位置。