I am trying to implement a line-draw feature with collision

Godot Version

Godot v4.2


To start, here’s the link to the player script:

And here’s a relevant screenshot.

I’m making a mobile game, but for the sake of fast development I’m using the mouse as the only input at the moment. I’m trying to implement it such that I can draw a line with the mouse, ( and if that line overlaps with that circle around the player (which is the attack range) then the player will attack in a direction parallel to the “attack line”.

I’m having some issues with this. I’d like to implement this with RayCast2D, so I can easily check for collision, but for some reason it’s position and direction are not what they should be. The red line in the screenshot is a ‘test line’ I implemented with a Line2D. The ‘anchor’ stays at the initial click position and the ‘head’ follows the mouse position, as it should. But the ray-cast, despite the values being reported as the same, does not look the same on screen. The anchor stays in the same place and the head moves when the mouse moves, but for some reason it’s not right on top of the Line2D like it should be.

I really don’t know what the issue is here. Debugging this is difficult. Any tips are appreciated, and let me know if any further info would be helpful.

Try setting the RayCast2D CanvasItem.top_level property to true so it does not inherit the position from the CharacterBody2D and won’t move with it and use its Node2D.global_position in line 69

1 Like

We’re making progress. Thanks for the global_position tip, now the ray is being anchored properly on every click. But for some reason the ray’s target_position is still kinda far away even on the initial click. I read in the docs that target_position is relative to RayCast2D’s position, which is probably the source of the problem somehow.

Yes, RayCast2D.target_position is local to the RayCast2D position. You’ll need to do something like ray_cast_2d.target_position = get_global_mouse_position() - ray_cast_2d.global_position or the other way around.

That did it, it’s now drawing correctly, thanks! I’m still having issues getting collision with the player’s attack range to work, but at least one problem is solved.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.