Compute relative position of a click in a child scene without using trig identities?

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

Does Godot have a built-in function for registering the translated position of a mouse click within a child scene?

Here’s the sample code for a simulation where you can pick up and throw objects about. (It includes emitting signals to my “world” scene for delegation.)

extends RigidBody2D

signal clicked
signal dropped

var held = false
var local_offset = Vector2.ZERO
var rotated_offset = Vector2.ZERO

func _input_event(viewport, event, shape_idx):
	if event.is_action_pressed("click"):
		local_offset = get_local_mouse_position()
		rotated_offset = rotate(local_offset)
		emit_signal("clicked", $Pin)

func _input(event):
	if event.is_action_released("click"):
		emit_signal("dropped", $Pin)

func rotate(coords):
	var x2 = cos(rotation)*coords.x - sin(rotation)*coords.y
	var y2 = sin(rotation)*coords.x + cos(rotation)*coords.y
	return Vector2(x2,y2)

With the rotate function, it translates the click position relative to the rotation of the child node, so the pickup doesn’t shift the center of the object to the mouse click.

Didn’t know if there was a Godot built-in one-liner for this sort of transformation.

I don’t know of any one liner, but could you just use to_global() and to_local() and base your position off of the global coords?

denxi | 2020-01-21 23:27

I may have been using it wrong, but those didn’t seem to take into account the rotation of the child scene when determining the position of the click within the area of the child object. I’ll take a closer look.

wallyfoo | 2020-01-21 23:35