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)
in Engine by (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)
by (29,120 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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.