用pygame和python跟踪玩家的摄像机

2024-10-03 21:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有50个外星精灵,我想跟踪玩家,但首先我要一个摄像头跟踪玩家去哪里。在

我在一个旧游戏中使用了这个功能,但是在我的旧游戏中,我没有使用类或精灵组,所以效率低下。在

所以在这个游戏中,我把玩家设置在屏幕中央,其他的东西都会移动,所以我有一个变量,比如CameraX和{},当玩家移动时,两个摄像机变量会上下移动。但是,在我的剧本里外星人没有更新。总之,这是我的脚本:

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()

然后是整个过程的脚本:

^{pr2}$

谢谢你的时间和帮助


Tags: keyrectimageselfeventif玩家screen
2条回答

关于摄像机: 在我看来,相机最简单的实现方式是a相机xoffset和camera yoffset。如果它被设置在x+y位置,则应将其设置为x+y位置

现在,如果我们希望玩家处于player_x位置,player_y位于屏幕中心,在每次迭代中:

我们正常更新播放器

我们将xoffset和yoffset设置为: xoffset=屏幕宽度/2-播放器 yoffset=屏幕高度/2-播放器

我们画了所有的精灵(包括玩家) 在位置sprite_x+x偏移,sprite_y+y偏移

冲洗并重复。我希望这有帮助:)

您不需要使用CameraXCameraY变量。相反,当你得到键盘输入时,只要让外星人都朝那个方向移动。你也没有任何代码可以移动玩家和外星人。您需要在类中添加一个update函数来更改源矩形的位置。在

相关问题 更多 >