0 votes

So I started working on a small RTS project and for that, I need to be able to select my Units.
I thought that I can create an Area2D with a Rectangle CollisionShape and then check if I'm overlapping with a Unit. For that, I need to resize and position the Area2D but I can't figure out on how to do it right.

Right now I achieved that the CollisionShape does change the Size when I drag, but not correct.

What I mean: Gif example
Green is how it should behave. Blue is how it does behave. Green is just a ColorRect which I got working by using set_begin() and set_end(). Blue is the CollisionShape which I haven't got to work

My node Setup:

  • Node2D

    • Camera2D (Here is the script running)
    • ColorRect ( The green thing that DOES work)
    • Area2D (The thing that does NOT work)

      • CollisionShape2D (Does not work)

My code right now for the Area2D:

export(NodePath) var selectionArea
var selectionCollisionShape

func ready():
     selectionArea = get_node(selectionArea)
     selectionCollisionShape = selectionArea.get_child(0)

func _process(delta):
    if Input.is_action_just_pressed("leftMouseButton"):
        selectionStart = get_global_mouse_position()

        selectionArea.position = selectionStart

    if Input.is_action_pressed("leftMouseButton"):
        selectionEnd = get_global_mouse_position()

        selectionCollisionShape.position = selectionEnd / 2
        selectionCollisionShape.shape.extents = selectionEnd / 2

So how do I correctly resize and position the Collisionshape/Area2D?

in Engine by (23 points)
edited by

1 Answer

+1 vote
Best answer

This should work:

var extents = selectionEnd - selectionStart
selectionCollisionShape.position = extents / 2
selectionCollisionShape.shape.extents = extents / 2

The position of the CollisionShape2D is relative to the position of it's parent (i.e. the Area2D's position), but you used a global position (i.e. relative to the origin at (0, 0)).

by (10,225 points)
selected by

Thank you!
That works like a charm!

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.