【问题标题】:Multiplayer Following Camera in PygamePygame中的多人跟随相机
【发布时间】:2020-09-28 07:32:51
【问题描述】:

对于一个学校项目,我正在使用 Pygame 在 python 中构建我们中间的娱乐。我已经设置了所有服务器和客户端代码,一切正常。我现在正在让相机跟随玩家。只有我不能让它工作。

我的想法是:当玩家移动时,他周围的一切都必须朝相反的方向移动。但是当你有一个多人游戏时,这是行不通的。因为这时其他玩家也会移动,这会破坏系统。

如果有人知道如何制作这样的代码,请告诉我。 提前谢谢你

【问题讨论】:

  • 你不需要自己移动对象,你只需要在偏移的位置绘制对象。代替“screen.blit(sprite.image, sprite.rect.topleft)”,执行“screen.blit(sprite.image, sprite.rect.topleft+camera_position)”。

标签: python pygame camera multiplayer


【解决方案1】:

您不必在播放器周围移动背景和对象矩形,您只需移动播放器并使用滚动偏移值来跟踪 blitted 对象必须偏移多少。您不会将滚动值应用于 rect 位置,因为 rect 位置不像 blit 对象那样相对于窗口。以下是您如何实现这一目标的示例。

import pygame, sys

clock = pygame.time.Clock()

from pygame.locals import *

pygame.init()

pygame.display.set_caption("Scrolling example")
WINDOW_SIZE = (600, 400)
screen = pygame.display.set_mode(WINDOW_SIZE, 0, 32)

scroll = [0, 0]
player = pygame.Rect(100, 100, 10, 10)
up = False
down = False
left = False
right = False

blocks = [pygame.Rect(250,250,50,50)]

while True:
    screen.fill((0, 0, 0))

    scroll[0] += (player.x - scroll[0] - (WINDOW_SIZE[0]/2)) // 20
    scroll[1] += (player.y - scroll[1] - (WINDOW_SIZE[1]/2)) // 20

    player_movement = [0, 0]
    if right == True:
        player_movement[0] += 2
    if left == True:
        player_movement[0] -= 2
    if up == True:
        player_movement[1] -= 2
    if down == True:
        player_movement[1] += 2

    player.x += player_movement[0]
    player.y += player_movement[1]

    player_scroll_rect = player.copy()
    player_scroll_rect.x -= scroll[0]
    player_scroll_rect.y -= scroll[1]

    pygame.draw.rect(screen, (255,255,255), player_scroll_rect)

    for block in blocks:
        scroll_block = block.copy()
        scroll_block.x = scroll_block.x - scroll[0]
        scroll_block.y = scroll_block.y - scroll[1]
        pygame.draw.rect(screen, (0,0,255), scroll_block)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                right = True
            if event.key == K_LEFT:
                left = True
            if event.key == K_UP:
                up = True
            if event.key == K_DOWN:
                down = True
        if event.type == KEYUP:
            if event.key == K_RIGHT:
                right = False
            if event.key == K_LEFT:
                left = False
            if event.key == K_UP:
                up = False
            if event.key == K_DOWN:
                down = False

    pygame.display.update()
    clock.tick(60)

如果您需要使用图像的解决方案,请咨询我。 此外,您可以在此处找到有关滚动的更多信息:https://www.youtube.com/watch?v=5q7tmIlXROg

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 2019-08-22
    相关资源
    最近更新 更多