Rotating a Node2D along a specified axis

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

Hi,

I’m trying to rotate a Node2D, including all of its children, along a specified axis. That is, I want the user to click on a part of a ColorRect and have the whole scene rotate around where the mouse is located. Is that possible, and if so, how would I achieve that?

Thanks!

:bust_in_silhouette: Reply From: avencherus

Sure, many ways of achieving it with inherited transforms of nodes. Using ColorRect and such, a Node2D as a pivot is the simplest way.

If I understood correctly, maybe something like this, though the effect is a bit unusual when keeping a large rectangle around some relative center point.

extends Node2D


var pivot : Node2D
var rect  : ColorRect


func resolution():

	return Vector2(
		ProjectSettings.get("display/window/size/width"),
		ProjectSettings.get("display/window/size/height"))


func add_sprite(p_node, p_pos):

	var s = Sprite.new()
	s.texture = preload("res://icon.png")

	p_node.add_child(s)
	s.position = p_pos


func _ready() -> void:


	pivot = Node2D.new()
	add_child(pivot)

	rect = ColorRect.new()
	pivot.add_child(rect)

	var res = resolution()
	var mid = res / 2.0

	rect.rect_size = resolution()
	rect.show_behind_parent = true

	update_pivot(mid)


	pivot.connect("draw", self, "dot")
	update()

	add_sprite(rect, mid + Vector2(-100, 100))
	add_sprite(rect, mid + Vector2( 200, 120))
	add_sprite(rect, mid + Vector2( 500, -20))


func dot():
	pivot.draw_circle(Vector2(), 3.0, Color.red)


func update_pivot(p_pos):

	pivot.position = p_pos
	rect.rect_position = -p_pos


var time  = 0.0
var speed = 1.0

func _physics_process(delta):

	time += delta * speed
	time  = fmod(time, TAU)

	pivot.rotation = time

	if(Input.is_mouse_button_pressed(BUTTON_LEFT)):
		update_pivot(get_global_mouse_position())