0 votes

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!

in Engine by (22 points)

1 Answer

0 votes

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())
by (5,192 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.