World position from event.position

Godot Version

Version 4.2

Question

Hi guys, I recently left Unity to join Godot and love it, but I keep running up against the same problem. I’m developing a 2D strategic game where you scroll back and forwards. All i want to do is place a sprite where i left click the mouse.

In unity c# it would be something like this:
spriteObject.transform.position = event.transform.position

But alas, the object vanishes and appears thousands of pixels away and nothing seems to work.

Here is a list of things I have tried so far:

I have tried both get_local_mouse_position() and get_global_mouse_position()
spriteObject.position = get_global_mouse_position()
I have tried using the camera, viewport, and canvas positions as offsets.
spriteObject.position = event.position + offset
I have tried converting to world space using:
var view_to_world = YOUR_NODE.get_canvas_transform().affine_inverse()
var world_position = view_to_world * view_position

I apologize if there is an obvious answer, but I’ve spent weeks stuck on it, and I can’t find anything that helps. Any assistance would be greatly appreciated.

Try spriteObject.global_position = get_global_mouse_position()
I don’t really know 2D but pretty sure that should work

1 Like

Yes i tried that to to no avail. But thanks for the suggestion all the same.

Can you please show the scene tree and point out the node, that you are trying to position and point out the node, that contains the script?

Recently a similar question was raised, but i’m not sure, if this scenario applies to your use-case: Checking if an event is within a collisionshape2d area - #4 by Sauermann

The event fires no problem. Its the positioning of the targeter which goes odd.
The script is on StateScreen_maps, the targeter is the object I need to move to the world position, where one would left-click.

What @Monday said should work. You said in your post that you tried spriteObject.position but @Monday said you should use spriteObject.global_position which are different.

func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.pressed:
			spriteObject.global_position = spriteObject.get_global_mouse_position()
			# This is the same as the line above
			# spriteObject.global_position = spriteObject.get_canvas_transform().affine_inverse() * event.global_position

More info about the coordinate system 2D coordinate systems and 2D transforms — Godot Engine (stable) documentation in English

1 Like

Yeah that fixed it. the error i made was this:
spriteObject.global_position = spriteObject.get_global_mouse_position()
I missed out spriteObject before get_global_mouse_position()

Thanks for all your help guys, you are legends. I’m really impressed by the Godot community so far.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.