实现2D相机的视角控制
脚本编写
该示例场景比较简单,主要就是脚本对于相机视角的控制,具体代码如下
extends Node2D
onready var camera = $Camera2D
var scaleNum = 2
var isDrag = fasle
var startPos = Vector2.ZERO
var startCamPos = Vector2.ZERO
func _ready():
camera.zoom = Vector2(scaleNum, scaleNum)
func _input(event):
if event is InputEventMouseButton:
# 缩放操作
if event.button_index == 4:
startPos = Vector2.ZERO
if scaleNum <= 0.1:
return
elif scaleNum >= 2:
scaleNum -= 0.3
else:
scaleNum -= 0.1
elif event.button_index == 5:
startPos = Vector2.ZERO
if scaleNum >= 10:
return
if scaleNum <= 0.3:
scaleNum += 0.03
elif scaleNum >= 8:
scaleNum += 0.6
else:
scaleNum += 0.1
# 移动操作
if event.button_index == 2 or event.button_index == 3:
if event.is_pressed():
isDrag = true
startPos = event.position
startCamPos = camera.position
else:
isDrag = false
startPos = Vector2.ZERO
if isDrag:
# 只有当在非缩放才会进行移动,避免边平移边缩放导致的图片跳动
if startPos != Vector2.ZERO:
var offset = startPos - event.position
camera.position = startCamPos + offset * scaleNum
func _process(delta):
camera.zoom = lerp(camera.zoom, Vector2(scaleNum, scaleNum), 8 * delta)