教你实现2D游戏中的小地图

场景的移动,旋转,缩放都能够实时显示到小地图上
场景搭建

效果如下图

并且我们将Camera2D的zoom属性设置为0.3,避免将背景地图全部照上。
勾选current属性,表示游戏窗口为当前的camera
勾选rotate属性,使得相机能够跟随player进行旋转
创建小地图

viewport
: 能够单独映射出一个场景进行渲染,使用它来作为小地图的输出,右键点击viewport
,点击Instance Child Scene
连接之前创建的game场景
viewportContainer
: 设置size大小属性,以及勾选Stretch
选项,即可在窗口看到效果

人物移动
为player添加移动的时候就会发现场景在小地图中也同步更新了
extends Sprite
var speed = 300
var rotate_speed = 2
func _process(delta):
var rotate_dir = 0
if Input.is_action_pressed("rotate_left"):
rotate_dir -= 1
elif Input.is_action_pressed("rotate_right"):
rotate_dir += 1
rotation += rotate_speed * rotate_dir * delta
var velocity = Vector2.ZERO
if Input.is_action_pressed("ui_right"):
velocity.x += 1
if Input.is_action_pressed("ui_left"):
velocity.x -= 1
if Input.is_action_pressed("ui_up"):
velocity.y -= 1
if Input.is_action_pressed("ui_down"):
velocity.y += 1
velocity = velocity.normalized()
position += velocity * speed * delta
小地图缩放
在场景根节点中创建脚本文件Main.gd
, 添加小地图缩放功能,以及替换人物图标
extends Node2D
var defaultMinimapScaleNum = 0.9
onready var minimap_player = $CanvasLayer/Control/ViewportContainer/Viewport/minimap/player
onready var minimap_enemys = $CanvasLayer/Control/ViewportContainer/Viewport/minimap/enemys
onready var minimap_camera = $CanvasLayer/Control/ViewportContainer/Viewport/minimap/player/Camera2D
func _ready():
setMinimapScale()
minimap_player.set_texture(load("res://assets/player.png"))
minimap_player.scale = Vector2(0.3, 0.3)
for ene in miimap_enemys.get_children():
ene.set_texture(load("res://assets/enemy.png"))
ene.scale = Vector2(0.3, 0.3)
func _input(event):
if event.is_action_pressed("scale_up"):
if defaultMinimapScaleNum <= 1.8:
defaultMinimapScaleNum += 0.1
elif event.is_action_pressed("scale_down"):
if defaultMinimapScaleNum >= 0.2:
defaultMinimapScaleNum -= 0.1
setMinimapScale()
func setMinimapScale():
minimap_camera.zoom = Vector2(defaultMinimapScaleNum, defaultMinimapScaleNum)
# 避免小地图的缩放影响到其他元素的大小
minimap_player.scale = Vector2(defaultMinimapScaleNum * 0.3, defaultMinimapScaleNum * 0.3)
for ene in miimap_enemys.get_children():
ene.scale = Vector2(defaultMinimapScaleNum * 0.3, defaultMinimapScaleNum * 0.3)