Godot Engine - 鼠标缩放及移动2D地图

文章目录

    • 功能需求
    • GDScript代码实现

功能需求

  • 鼠标滚轮缩放地图
  • 鼠标点击拖动地图

GDScript代码实现

Project--Project Settings--Input Map选项卡中,绑定上下滚轮及鼠标单击输入

TileMap创建一个Camera2D子节点
选中Current保证相机运行
右键点击“添加脚本”

extends Camera2D
var pull = false
var mousePos
var currentPos
func _physics_process(delta):
	if Input.is_action_just_released("ScrollUp"):
		if zoom.x >= 0.8 and zoom.y >= 0.8:
			zoom.x -= 0.2
			zoom.y -= 0.2
	if Input.is_action_just_released("ScrollDown"):
		if zoom.x <= 4 and zoom.y <= 4:
			zoom.x += 0.2
			zoom.y += 0.2
	if Input.is_action_just_pressed("LMB"):
		mousePos = get_global_mouse_position()
	if Input.is_action_just_released("LMB"):
		pull = false
		currentPos = get_global_mouse_position()
		offset.x -= currentPos.x-mousePos.x
		offset.y -= currentPos.y - mousePos.y

实现简单的点击拖动和滚轮缩放。

下面是改进后的代码,能实现持续拖动。

extends Camera2D
var pull = false
var mousePos
var currentPos
func _physics_process(delta):
	if Input.is_action_just_released("ScrollUp"):
		if zoom.x >= 0.8 and zoom.y >= 0.8:
			zoom.x -= 0.2
			zoom.y -= 0.2
	if Input.is_action_just_released("ScrollDown"):
		if zoom.x <= 4 and zoom.y <= 4:
			zoom.x += 0.2
			zoom.y += 0.2
	if Input.is_action_just_pressed("LMB"):
		mousePos = get_global_mouse_position()
	if Input.is_action_pressed("LMB"):
		currentPos = get_global_mouse_position()
		offset.x -= currentPos.x-mousePos.x
		offset.y -= currentPos.y - mousePos.y

你可能感兴趣的:(Godot,Engine,游戏开发)