Search code examples
linegodotgdscript

How to make a new created line of specific length?


I need the line I am drawing to be of specific length. I can detect when it reaches the required length but if the user moves the mouse faster it could make the line longer than intended.

Heres a video of the issue I am having, when I move the mouse slowly works great but speed gives issue: https://www.youtube.com/watch?v=4wkYcbG78TE

Here is the code where I create and detect the length of the line.

if Input.is_action_pressed("Left_click"): #This checks the distance between last vector and the mouse vector
        #points_array[-1] = get_global_mouse_position() # Gets the last position of the array and sets the mouse cords
        var length = clamp(points_array[-1].distance_to(get_global_mouse_position()),0,20)
        if length == 20: # if its long enough create a new line and set it to mouse position
            var cords = get_global_mouse_position()
            print(cords)
            points_array.append(cords)

Solution

  • When the mouse moved too much, you could add multiple points to fill the gap, always at the correct distance, of course.

    That is, while the length from the last point to the position of the mouse is larger than the distance you want, add another point at the appropriate distance.

    Thus, a while loop:

    if Input.is_action_pressed("Left_click"):
        var mouse_pos = get_global_mouse_position()
        var distance = 20
        while points_array[-1].distance_to(mouse_pos) > distance:
            var cords = # ???
            points_array.append(cords)
    

    A little vector algebra will figure out where to place that point. Starting from the last added point, you want to go in the direction from it to the position of the mouse. What distance to go? well, it the length you want.

    if Input.is_action_pressed("Left_click"):
        var mouse_pos = get_global_mouse_position()
        var distance = 20
        while points_array[-1].distance_to(mouse_pos) > distance:
            var last_point = points_array[-1]
            var cords = last_point + last_point.direction_to(mouse_pos) * distance
            points_array.append(cords)
    

    I believe that should work.