0 votes

I am trying to draw a line from the player to the mouse. I know how to use _draw() function to draw between a static point and the mouse, but how do I update my position so that the line is always being drawn from the node?

func _draw():
     var player_pos = get_node("Player/Weapon").get_pos()
     var mouse_pos = get_node("Player/Weapon").get_local_mouse_pos()
     player_pos.normalized()
     mouse_pos.normalized()
     draw_line(player_pos, mouse_pos, Color(0, 0, 0), 1)
asked Apr 4, 2018 in Engine by CosmicNerd6505 (22 points)

1 Answer

0 votes

Assuming you use Godot 2.1.x:

# I assume this script is on a Node2D which is parent or the player.
# This means it will not draw things relatively to the player,
# but relative to the world (I guess?)
func _draw():

    # get_pos() returns the local position of the Weapon, relative to the Player.
    # So this is not going to be the position relative to the world,
    # your line won't show at the right place.
    var player_pos = get_node("Player/Weapon").get_pos()

    # Same here, you are getting mouse pos relative to the weapon.
    var mouse_pos = get_node("Player/Weapon").get_local_mouse_pos()

    # This function doesn't modify the variable.
    # It returns a new one, but you are not storing it anywhere,
    # so it does nothing.
    # Also, the purpose of that function is to shorten the vector
    # to a length of 1, which is probably not what you want.
    player_pos.normalized()
    mouse_pos.normalized()

    draw_line(player_pos, mouse_pos, Color(0, 0, 0), 1)

So there are two solutions.
You can do this in your current drawing script by using global positions instead (assuming it's indeed the root of the level and is placed at the origin):

func _draw():
     var player_pos = get_node("Player/Weapon").get_global_pos()
     var mouse_pos = get_global_mouse_position()
     draw_line(player_pos, mouse_pos, Color(0, 0, 0), 1)

Or, you could move that function to a script which is on the Player node.
In which case, this will work with local positions:

func _draw():
     var player_pos = get_node("Weapon").get_pos()
     var mouse_pos = get_local_mouse_position()
     draw_line(player_pos, mouse_pos, Color(0, 0, 0), 1)
answered Apr 5, 2018 by Zylann (27,008 points)

Thanks, that helped a lot! I guess you can tell, I'm kinda new at GDscript, so thanks for the patience

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.