How to update position of a node?

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

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)
:bust_in_silhouette: Reply From: Zylann

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)

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

CosmicNerd6505 | 2018-04-05 01:39