#How to access a temp variable in another function? (2D grappling hook)

7 messages · Page 1 of 1 (latest)

bitter mortar
#

Hey, im new to godot and making my first project thats not just a copy of a video tutorial. Im trying to make it so that when the player shoots a grappling arrow, it constantly updates adding points to a line2D node between the player and the arrow.

The arrow is instantiated in a normal function, and I dont know how to access the temp arrow variable in a delta function to have it constantly update. I also tried to update the line2D in the arrow scene itself, but I wasnt sure how to access the players location from the arrow scene.

any help would be greatly appreciated, i have been struggling with this for a long time.

#

in the video I changed:

if grappled == true:
pass

woven zealot
#

Because of scoping, it's not possible to access a variable declared within another function as you're trying to do. You have a couple of different options to use instead here:
First, you could make link a variable in global scope, so declared outside of the function. This would work, as you're already making use of grappled to check whether or not to add points, so you don't need to check if the link variable is null/unassigned, as it will always be assigned so long as grappled is true.
The other, better option is one you've already alluded to, which is to update the line2D from the arrow scene. To access the player's location in the arrow scene, you just need to give the arrow a way to access the player node. If this is a singleplayer game (and if it's likely that you'll need other scripts to find the player node) I would consider doing this with an autoload, but assuming you just specifically want to pass it in to the arrow scene:

  1. Add a new global scoped variable to the arrow's script, var player (or, with typing, var player : Node2D)
  2. In your grapple() function in the player script, set the player for the instantiated arrow with grappleArrowTemp.player = self
  3. To get the location of the player node within the arrow script, use player.position

In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts of the program, the name may refer to a different entity (it may have a different binding), or to not...

bitter mortar
#

I used autoload to make the player variable global, but im still having one problem. Anytime I try to get the position from the player, I get this error message,

Invlalid get index 'position' (on base: 'PackedScene').

bitter mortar
#

It works now