Resize and position CollisionShape2D with mouse for a selectionbox

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

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?

:bust_in_silhouette: Reply From: njamster

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)).

Thank you!
That works like a charm!

Tim Irmler | 2020-07-17 15:40