How to move 2D Editor view to another position from a tool script

Godot Version

4.3

Question

I’m making a plugin where I can click a button and then zoom in and center on a node in a scene. I’m not sure how to properly transform the 2D Editor view. I’d like to center on a node and then keep the view there so I can easily go edit it and its surroundings.

I’ve tried this code as a test. It should put the origin in the upper left corner and set the zoom to 100%

	var tf = Transform2D(Vector2(1,0), Vector2(0,1), Vector2())
	view.global_canvas_transform = tf

I think it is indeed transforming the view, but as soon as I hover the mouse back over the viewport it snaps back to where it was. Additionally, the side bars with the measurements and the zoom amount don’t change on the interface. Is there an established way to achieve this?

1 Like

Did you end up finding a solution? I’d like to know this as well!

1 Like

This is the gross way you can center something in the editor.

func _center_editor_view_to_point(pos: Vector2, zoom: float = 100.0) -> void:
	if not Engine.is_editor_hint():
		return
	
	var editor_viewport: Control = EditorInterface.get_base_control().find_child("@CanvasItemEditorViewport*", true, false)
	
	@warning_ignore("untyped_declaration")
	var zoomer = editor_viewport.find_child("@EditorZoomWidget*", true, false)
	
	@warning_ignore("unsafe_method_access")
	zoomer.set_zoom(zoom)
	
	@warning_ignore("unsafe_property_access")
	@warning_ignore("unsafe_method_access")
	zoomer.zoom_changed.emit(zoom)
	
	# add offset to center
	pos -= (editor_viewport.size / zoom) / 2.0
	
	var hscroll: HScrollBar = editor_viewport.find_child("@HScrollBar*", true, false)
	hscroll.value = pos.x
	var vscroll: VScrollBar = editor_viewport.find_child("@VScrollBar*", true, false)
	vscroll.value = pos.y