Python 如何在pygame中创建平滑的摄影机运动?
我看过很多关于在2D侧滚游戏中实现简单相机的不同方法的帖子。我处理这个问题的方法是制作一个物体,只要玩家在屏幕上居中,而不是在屏幕的末端,它就会偏移所有物体的位置 这是绝对好的,但我想考虑更大的问题 我想知道我怎么能添加平滑的摄像机运动,玩家不只是一直停留在屏幕中央,而是相机实际上是跟随玩家。在寻找答案的过程中,我找到了仅在Java中可用的示例。但我不确定如何在pygame中添加此功能。如果你认为你可以向我解释如何实现这一点,那将是非常有帮助的Python 如何在pygame中创建平滑的摄影机运动?,python,pygame,Python,Pygame,我看过很多关于在2D侧滚游戏中实现简单相机的不同方法的帖子。我处理这个问题的方法是制作一个物体,只要玩家在屏幕上居中,而不是在屏幕的末端,它就会偏移所有物体的位置 这是绝对好的,但我想考虑更大的问题 我想知道我怎么能添加平滑的摄像机运动,玩家不只是一直停留在屏幕中央,而是相机实际上是跟随玩家。在寻找答案的过程中,我找到了仅在Java中可用的示例。但我不确定如何在pygame中添加此功能。如果你认为你可以向我解释如何实现这一点,那将是非常有帮助的 万一你不知道我所说的相机平滑运动是什么意思,你可以
万一你不知道我所说的相机平滑运动是什么意思,你可以浏览一下,大致了解一下我在说什么。正如我已经提到的,你能给我的任何提示或出发点都会非常有用。你可以用向量来做这件事。我只是用一个向量作为相机,让它跟随播放器。首先从player.pos中减去相机,得到另一个称为heading的向量,该向量从相机指向播放器。然后将该矢量缩放到所需速度(长度的一小部分),并将其用作摄影机的速度
from random import randrange
import pygame as pg
from pygame.math import Vector2
class Player(pg.sprite.Sprite):
def __init__(self, pos, *groups):
super().__init__(*groups)
self.image = pg.Surface((30, 30))
self.image.fill(pg.Color('dodgerblue1'))
self.rect = self.image.get_rect(center=pos)
self.pos = Vector2(pos)
self.vel = Vector2(0, 0)
def handle_event(self, event):
if event.type == pg.KEYDOWN:
if event.key == pg.K_d:
self.vel.x = 5
elif event.key == pg.K_a:
self.vel.x = -5
elif event.key == pg.K_w:
self.vel.y = -5
elif event.key == pg.K_s:
self.vel.y = 5
elif event.type == pg.KEYUP:
if event.key == pg.K_d and self.vel.x > 0:
self.vel.x = 0
elif event.key == pg.K_a and self.vel.x < 0:
self.vel.x = 0
elif event.key == pg.K_w:
self.vel.y = 0
elif event.key == pg.K_s:
self.vel.y = 0
def update(self):
# Move the player.
self.pos += self.vel
self.rect.center = self.pos
def main():
pg.init()
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
camera = Vector2(400, 300)
player = Player((400, 300), all_sprites)
background_rects = [pg.Rect(randrange(-3000, 3001), randrange(-3000, 3001), 20, 20)
for _ in range(500)]
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
player.handle_event(event)
all_sprites.update()
# A vector that points from the camera to the player.
heading = player.pos - camera
# Follow the player with the camera.
# Move the camera by a fraction of the heading vector's length.
camera += heading * 0.05
# The actual offset that we have to add to the positions of the objects.
offset = -camera + Vector2(400, 300) # + 400, 300 to center the player.
screen.fill((30, 30, 30))
# Blit all objects and add the offset to their positions.
for background_rect in background_rects:
topleft = background_rect.topleft + offset
pg.draw.rect(screen, (200, 50, 70), (topleft, background_rect.size))
screen.blit(player.image, player.rect.topleft+offset)
pg.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
pg.quit()
哇,非常感谢。我以前不认为使用向量有什么意义,但现在你启发了我。