How to make a selection of next unit via arrow key relative to current selection?

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

Hi, so I am trying to accomplish a selection from whenever you press an arrow key, it will find the nearest selectable unit on the direction of the pressed key and select that unit.

For example, currently I am at the center position, so whenever I press the UP key, the top position will be selected. But if I press the UP key again, the selection will cycle back to the bottom position. And pressing the UP key again will bring the selection back to the center.

I tried using two-dimensional Array and load each position into the Array, and whenever a key is pressed it will either subtract or addition depending on the direction to make the selection, although this will only work if the position are not moving.

var enemy_party = [[$Enemy1, $Enemy2, $Enemy3], [$Enemy4, $Enemy5, $Enemy6], [$Enemy7, $Enemy8, $Enemy9]

I am planning to make the enemies move so the position will change, how should I approach this?

:bust_in_silhouette: Reply From: The_Black_Chess_King

Maybe you could calculate it using Vector2()?

Assuming the arrow you said were the keyboard arrows, in theory the way I would try to implement this would be:

onready var Direction = Vector2()

#in your main loop for movement

match Direction: 
if Input.is_action_pressed('Left'):Direction.x = -1
if Input.is_action_pressed('Right'):Direction.x = 1
if Input.is_action_pressed('Down'):Direction.y = 1
if Input.is_action_pressed('Up'):Direction.y = -1
#Note that this is a diagonal direction Vector2(1,1)

Using 1 raycast to follow the current selected unit, on it’s center to get cast in the direction of the Vector2(), and return any other unit that has crossed the ray, would be possible to specifying a max distance for the raycast as well by returning it’s length.

Oh and for the switching from up to bottom, you could do Vector2().y = *-1 to invert the direction.

The_Black_Chess_King | 2020-05-06 14:24