Need some way for a tool script to move a node to always track to the center of the 2D editor camera

Godot Version

4.4.stable

Question

I am trying to find a way to make an object snap to the center of the camera in editor, even when i pan or zoom in or out on the canvas.

I have gotten as far as typing:

@tool
extends Node
var EditorCamPosition : Vector2
func _process(_delta):
	if Engine.is_editor_hint():
		EditorInterface.get_editor_viewport_2d()

I have tried:

EditorInterface.get_editor_viewport_2d().global_canvas_transform.origin

but the coordinates are completely different than expected. x is negative to the right instead of positive and the numbers are affected by zooming in and out.

EditorInterface.get_editor_viewport_2d().get_screen_transform().origin

again, there are coordinates but they are completely different from what I would expect.

EditorInterface.get_editor_viewport_2d().get_final_transform().origin

but again the coordinates are completely different from what the bar at the top shows me.

If there’s any way to convert these coordinates to match what they are on the ruler guides on the top and left, that would be amazing or perhaps I’m just going about it completely wrong. I don’t know. Any help would be appreciated.

Could you use the forum’s formatting for your code so we can read it a bit better? Should look like This:

var example 
something something code magic

You can use the buttons at the top when replying to format.

Fixed. Sorry I wasn’t aware of how to actually write code in this forum until now.

1 Like

Messed around myself for a bit, i unfortunately couldn’t get anything either. Sorry :confused: this one’s a toughy. Hopefully someone here can help, signaling assistance squad :flashlight:

1 Like

You might be able to get the camera from the viewport, I’ve done something similar in 3D

var camera := EditorInterface.get_editor_viewport_2d().get_camera_2d()
EditorCamPosition = camera.global_position

Viewport.global_canvas_transform origin gives you the top-left corner of the canvas (where the red and green lines cross) so it will have negative x when you scroll the canvas to the left and changing the zoom will change the position of the top-left corner of the canvas

@tool
extends Node


func _process(delta: float) -> void:
	var vp = EditorInterface.get_editor_viewport_2d()
	var transform = vp.global_canvas_transform
	var center = transform.affine_inverse() * (vp.size / 2.0)
	$Sprite2D.global_position = center

Result:

Here’s more information:

2 Likes

This is exactly what I need, but where did you put this code to get it to work?

In any node of your scene you need to. That’s up to you.

1 Like

if I just attach this script to my main node and have a sprite2d child node, shouldn’t it move it? It doesn’t seem to do anything for me.

Try reloading the scene after adding the script.

1 Like

Okay it was just a little bit finnicky. Thanks for this. You’re a lifesaver!

I appreciate your efforts to help!