get middle of rect ?

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

So is this the correct way to get the middle of an object that has rect position/rect size/rect scale?

var el = $ColorRect
var x = el.rect_position.x + ((el.rect_size.x * el.rect_scale.x) / 2)
var y = el.rect_position.y + ((el.rect_size.y * el.rect_scale.y) / 2)
var middle_position = Vector2(x, y)

It works, but it looks really messy. Is there a handy function that does the same?

Also, when working with nodes that doesn’t have rect properties, is there any other way to get the middle position cleanly?

Could you access the end property of the Rect2 and directly divide that vector by 2? Maybe you could do something like this: var obj = el.rect_position.end / 2

I haven’t tried this, but it may work.

Ertain | 2018-06-25 17:05

Your code can be easily compressed into:
var middle_position = el.rect_position + el.rect_scale*el.rect_size/2.0
Notice that:

  1. You can add and multiply vectors directly to each other. So you don’t need to work on the components separately.

  2. Addition has a lower precedence than multiplication and division; so the parentheses can be removed.

SIsilicon | 2018-06-25 18:05