# How to extend a line to infinity?

In my game I have a line that simulates the trajectory of a gun shot, fired by the main character.

The line starts at the character and ends at the mouse position at the moment of the click.

What happens is that sometimes the click is before the target. So the line does not extend to the target. I wish I could extend the line, at least to the end of the room.

What happens:

What I would like to happen:

Line:

(x1,y1,x2,y2)

(obj.x,obj.y,mouse_x,mouse_y)


• I would recommend looking up point lasers, or laser beams tutorials for GMS2, there are various ways to approach this. May 11 '21 at 6:58
• @Steven I've seen some. They work with objects. I would just like to create a line to use in the function: collision_line May 11 '21 at 13:26

The problem is simpler than it looks.

I had already seen something similar looking for a laser. But this was done using objects, increasing their scale on the x-axis and changing the rotation.

Based on that, I looked for angled lines and I found this:

New Line:

draw_line(x1,y1,x2,y2);

aux=point_direction(obj.x,obj.y,mouse_x,mouse_y);

auxDsin=dsin(aux);
auxDcos=dcos(aux);

draw_line(obj.x,obj.y,obj.x+(1920*auxDcos),obj.y+(-1920*auxDsin));


I used 1920 because it is the size of the screen.

You can draw a line along a given direction using the lengthdir_*() functions.

First, you find out the direction from your object towards the mouse pointer with point_direction():

var dir = point_direction(obj.x, obj.y, mouse_x, mouse_y);


Then, you draw a line with this direction (in the object's Draw Event):

var len = 1920;
var to_x = lengthdir_x(len, dir);
var to_y = lengthdir_y(len, dir);
draw_line(obj.x, obj.y, obj.x + to_x, obj.y + to_y);


The line starts at point (obj.x, obj.y) and has direction dir (in degrees) and length len. The length can be changed as it better suits your needs, since GM:S doesn't let you pick infinity as a numeric value.

• The line is not coinciding with the bullet's trajectory and at no time does it click with the mouse. May 12 '21 at 23:42
• I added an image showing what happens when I use your answer. May 12 '21 at 23:47
• The lengthdir_*() function computes vector components along the x and y axes given the length and direction of the reference vector. Since such vector is a direction and not a position, it must be added component-wise to the starting point in order to get the destination point. I updated my answer and fixed my code snippet accordingly. May 13 '21 at 7:42