How to zoom and pan a node2D?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MikaelT

How can i make something like this in Godot?

Link: http://phrogz.net/tmp/canvas_zoom_to_cursor.html

Pan: Drag with mouse
Zoom: Use mouse wheel or click (and shift-click). Zoom will zoom at to mouse position.

I have spend more than 7 hours to make something similar in Godot. I’m stuck. Please help. Thanks.

/Mikael

What code do you have so far?

Magso | 2019-08-01 18:22

In my 3rd try, I started a new project, so any existing code did not “blur” my hunt for a solution.

Here is the code:

extends Node2D

var zoom = 1
var p1 = 0

func _ready():
	set_process_input(true)
	set_process(true)
	
func _process(delta):
	$Label.text = "Zoom: "+str(zoom)+" Mouse: "+str(get_global_mouse_position()) + "    Local: " + str(get_local_mouse_position())+ \
		"\nPos: "+str(position) + \
		"\nSpr:"+str($Sprite9.position) + \
		"\nP1: "+str(p1)

func _input(event):
	if Input.is_action_just_pressed("cam_zoom_in"):
		AdjustZoom(0.1)
	if Input.is_action_just_pressed("cam_zoom_out"):
		AdjustZoom(-0.1)
	if Input.is_action_just_pressed("test"): 
		zoom = 1
		AdjustZoom(0)

func AdjustZoom(amount):
	zoom += amount

	$Sprite9.position = get_local_mouse_position()
	
	var local = get_local_mouse_position()
	if (amount != 0):
		p1 = (1-zoom)*get_local_mouse_position()
	print("->zoom: "+str(zoom)+ " ("+str(amount)+")")
	position = p1

	scale.x = zoom
	scale.y = zoom
	
static func IsEqual(a, b, epsilon = 0.00001):
    return abs(a - b) <= epsilon

Right-Click and select "Show Image" to see screenshot of running project

Right-Click and select "Show Image" to see screenshot of project

MikaelT | 2019-08-01 18:47

:bust_in_silhouette: Reply From: BraindeadBZH

I have written an article on that: check here
Use the the version for Godot 3.

Thanks. Looks perfect!

I will check it out tomorrow (I’m traveling today).

/Mikael

MikaelT | 2019-08-03 05:31

Great script!

You have saved me hours of work.

Please tell me how I can thank you. Perhaps a cup of coffee? :slight_smile:

Regards,
Mikael

MikaelT | 2019-08-04 18:52

Don’t worry, help is provided for free here, we just ask that you help others whenever possible.

BraindeadBZH | 2019-08-04 20:51

Link is dead, but archived here:

Godot Quick Tip #1 - Interactive Camera2D | Braindead.bzh

opyate | 2023-02-02 18:11