[英]How would I go about creating smooth camera movement in pygame?
我已經看過許多關於在2D側滾動游戲中實現簡單相機的不同方法的文章。 我的解決方法是,只要播放器位於屏幕中央而不是屏幕末端,就可以制作一個使所有位置都偏移的對象。
這絕對可以,但是我想更大一點。
因此,我想知道如何添加“平滑的攝像頭移動”,即播放器不總是一直停留在屏幕中間,而是攝像頭實際上在跟隨播放器。 為了尋找答案,我找到了僅在Java中有效的示例。 我不確定如何在pygame中添加此功能。 如果您認為可以向我解釋如何實施,那將很有幫助。
萬一您不知道我所說的“平穩的相機運動”是什么,您可以瀏覽此視頻以了解我在說什么。 正如我已經提到的,您可以給我的任何提示或起點都將非常有幫助。
您可以使用矢量來做到這一點。 我只是在這里使用矢量作為相機,使其跟隨玩家。 首先從player.pos
減去camera
,以獲得另一個從相機指向播放器的向量(此處為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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.