Struggling to implement my Idea

Godot Version

4.5.1

Question

I had an Idea to make a game with a "spider-man" like mechanic you play as a spider and you use your string to attach on to other points I have tried to make a prototype but it just does not seem to work so I was hoping for some ideas from you guys.I should add that I am a beginner

Here is my code:

It instantiates a ray and checks for collision and then it takes a point for the collision after that I make a line connecting from the player to the poiint clicked but as you can see it just doesn’t seem to work.

(Rays and lines do not match up)

Thank you in advance ! I am going to sleep so it will be 8 hours before I reply sorry

var max_distance = 500

func shoot_ray(target_pos: Vector2):
	var attach_point
	var ray = RayCast2D.new()
	ray.enabled = true
	add_child(ray)
	ray.position = string.position
	ray.target_position = (target_pos - global_position).normalized() * max_distance
	ray.add_exception(self) # optional, so the ray doesn’t hit the player
	ray.force_raycast_update()
	if ray.is_colliding():
		attach_point = ray.get_collision_point()
		print("Attach point:", attach_point)
		return attach_point
	ray.queue_free()
	if not ray.is_colliding():
		ray.queue_free()
		return Vector2.ZERO



func line_position(x):
	var line = Line2D.new()
	add_child(line)
	print("line")
	line.width = 10
	line.add_point(string.position)
	line.add_point(x)

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("Left_Click"):
		var pos = get_global_mouse_position()
		select.position = pos
		print(pos)
		var attach_point = shoot_ray(pos)
		line_position(attach_point)
		

And node structure

If i remember correctly the points of the line have to be the local_position and not the global_position

try this and see if it improves:

func line_position(x):
	x = to_local(x)
	var line = Line2D.new()
	add_child(line)
	print("line")
	line.width = 10
	line.add_point(string.position)
	line.add_point(x)

I second what @herrspaten mentioned

But you also need to take the local mouse position here:

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("Left_Click"):
		var pos = get_local_mouse_position()
		select.position = pos
		print(pos)
		var attach_point = shoot_ray(pos)
		line_position(attach_point)

why would we use local mouse_position instead of global mouse position ? I do not understand why you would pick one over another neither the difference

Let me take this even further would we not prefer to use global_position more because the local_position is relative to our node?

Raycasting happens in global space, so use global coordinates for that. Line points are specified in line node’s local space, so use local coordinates for that. It’s just a matter of proper transformation of coordinates to/from each space.