Python Pygame 相机运动 [英] Python Pygame Camera Movement

查看:42
本文介绍了Python Pygame 相机运动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在使用 Pygame 用 Python 制作一个 2d 俯视图游戏.我一直在尝试创建一个让玩家保持在屏幕中央的相机运动.我该怎么做?我想将地图"放在一个表面上,它将被 blit 到屏幕表面.如果这样做,我可以只构建一次地图,然后以某种方式调整它的位置,以便玩家始终停留在屏幕的中心.我的播放器像这样更新它的位置:

So, I'm making a 2d topviewed game in Python with Pygame. I've been trying to create a camera movement that would keep the player in the center of the screen. How would I do this? I'd like to have the "map" in a single surface, that will be blit to the screen surface. If doing so I could just build the map once and then just somehow adjust it's position so that the player will always stay in the center of the screen. My player updates it's position like this:

   def update(self, dx=0, dy=0):
        newpos = (self.pos[0] + dx, self.pos[1] + dy)  # Calculates a new position
        entityrect = pygame.Rect(newpos, self.surface.get_size())  # Creates a rect for the player
        collided = False
        for o in self.objects:  # Loops for solid objects in the map
            if o.colliderect(entityrect):
                collided = True
                break

        if not collided:
            # If the player didn't collide, update the position
            self.pos = newpos

        return collided

我发现了这个,但那是针对侧视平台游戏的.所以我的地图看起来像这样:

I found this, but that was for a sideviewed platformer. So my map would look something like this:

map1 = pygame.Surface((3000, 3000))
img = pygame.image.load("floor.png")
for x in range(0, 3000, img.get_width()):
    for y in range(0, 3000, img.get_height()):
        map1.blit(img, (x, y))

那么我将如何进行相机移动?任何帮助将不胜感激.

So how would I do the camera movement? Any help would be appreciated.

附注.我希望你能明白我在这里问的是什么,英语不是我的母语.=)

PS. I hope you can understand what I'm asking here, english is not my native language. =)

推荐答案

好吧,您没有展示如何绘制地图或播放器,但您可以这样做:

Well, you didn't show how you draw your map or your player, but you can do something like this:

camera = [0,0]
...
def update(self, dx=0, dy=0):
    newpos = (self.pos[0] + dx, self.pos[1] + dy)  # Calculates a new position
    entityrect = pygame.Rect(newpos, self.surface.get_size())
    camera[0] += dx
    camera[1] += dy
    ...

然后你像这样绘制你的地图

Then you draw your map like this

screen.blit(map1, (0,0), 
            (camera[0], camera[1], screen.get_width(), screen.get_height())
           )

这样地图就会向相机的相反方向滚动,让玩家保持静止.

This way the map will scroll in the opposite direction of the camera, leaving the player still.

如果您不想让玩家在您的世界中移动,但不想在屏幕中移动,您可以执行以下操作:

If you wan't the player to move in your world, but not to move in the screen, you can do something like this:

screen.blit(player, (player.pos[0]-camera[0], player.pos[1]-camera[1]))

这篇关于Python Pygame 相机运动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆