How to dynamically change RayCast2D's position?

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

I’ve got a 2d top-down space game, visually similar to Space Rock, which y’all know very well

I have a randomly spawned enemies and a want to spawn them by two and have drawn a line between them. This line moves and changes it’s length relatively to the positions of spawned NPC’s and move with them together.
Also I’ve got a RayCast2D node, which should check if something collide with this line between NPC’s. I tried to do this.
I added node RayCast2D as a child to node Line2D.
TargetLine.gd code:

func _process(delta: float) -> void:
if is_instance_valid(target1) and is_instance_valid(target2):
	points[0] = to_local(target1.global_position)
	points[1] = to_local(target2.global_position)
	$Ray_collision_checker.set_cast_to(to_local(target2.global_position))
	$Ray_collision_checker.set_position(to_local(target2.global_position))

target1 and 2 are positions of the 2 NPC’s, where the line has points. And when I try to set the position of a raycast and to set it’s cast direction it just sets the position correctly(or maybe it’s already set well because it’s child node) but the cast direction is located somewhere far in space, and I have generally no idea, why. I can provide any further info, and… thanks in advance.

:bust_in_silhouette: Reply From: aXu_AP

Hi again :slight_smile:
It seems that you set both of them to target2’s position. But there’s a second problem lurking. The cast position is in local space of the raycast itself. Hence you cannot use the parent’s (Line2D’s) to_local function. The solution is to use RayCast2D’s to_local.

# Godot also allows to modify global_position, so no need to use to_local here
$Ray_collision_checker.global_position = target1.global_position
# Use ray's local transform here
$Ray_collision_checker.set_cast_to($Ray_collision_checker.to_local(target2.global_position))

Dude, you helped me so much, twice. I hope everyone in need can find such a mentor))

Yozhik | 2021-10-18 18:17

I too do need help from time to time. So it’s nice to be able to give back to the community whenever I have time and energy :slight_smile:

aXu_AP | 2021-10-18 18:52