find the intersection point from an origin and direction (vec2D) with the limits of the map

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

Hi all !

I need help to solve a vector 2D problem. In my project, a 2D isometric game, I’m trying to implement the gun fire logic. The player aims using his mouse cursor in a way that when he shoots, the “bullet” follow a line that starts from his position and ends on the mouse position.

For that I use Raycasting technique as explained in Ray-casting — Godot Engine (3.0) documentation in English and the method Dictionary intersect_ray ( Vector2 from, Vector2 to, Array exclude=[ ], int collision_layer=2147483647 )

For the moment, it works very well, collisions are detected correctly but only between the player position and the mouse position. What I want instead is to find the coordinates of the intersection point between the “line” formed by the player position, the cursor position and the map boundaries. So the second point that I’ll pass to intersect_ray will be located somewhere on the boundaries of the map. In this way the collisions will be checked from the player position and until the line reach the map boundaries.

Just to be sure you can check the images bellow to clarify what I’m talking about. Just imagine that the image borders are the map boundaries.

this is what I have currently

this is what I want

I don’t know how to approach the problem. Have you idea ? Do you have any ideas ?

:bust_in_silhouette: Reply From: p7f


For defining the position of end of the RayCast, you need angle and magnitude. So you could get the angle like this (assuming you have the origin position stored in variable from):

var angle = from.angle_to_point(get_global_mouse_position())

Then you can define the ending position by making a looong vector with that angle, and summing it to from vector, like this:

var to = (from + Vector(5000,0).rotated(angle)) #adjust 5000 to maximum distance possible between to points in map

Then just raycast from from to end

This is as much i can imagine without code. If you share code or project maybe i or someone can help you more.

Thank a lot for your answer ! Your suggestion works well. I just had to subtract 180 degree from the angle because the produced vector was at the opposite side
var to = global_position + Vector2(5000,0).rotated(angle - deg2rad(180))

About my code I will try to post the relevant part.

doums | 2019-01-08 17:55

You are welcome. Is the issue is solved, there is no need to post the code. You may also select the answer if it worked so others can see its solved.

p7f | 2019-01-08 17:56