How do you stop a tween?
I want to end my tween process when my character body exits an area2d.
How do you stop a tween?
I want to end my tween process when my character body exits an area2d.
NJL64 Call Tween::kill() on the tween object. You'll need to keep a reference to it in a non-local variable so you can access it from the signal handler.
Declare the variable at the top of the script:
var tween: Tween
In _on_laser_body_entered:
tween = create_tween()
DaveTheCoder Thanks. I think I've almost got it, but now when the body exits the area2D, I get the error: "cannot call method 'kill' on a null value."
NJL64
Do exactly as @DaveTheCoder said.
In _on_laser_body_entered()
, instead:
var tween = create_tween()
do:
tween = create_tween()
DaveTheCoder thank you so much. Just so I understand how it works, how come getting rid of "var" did the trick?
NJL64 How come getting rid of "var" made it work?
When you use var
you declare a new variable. If you declare a variable inside a function then that variable is local to function. If, at the same time, the script-wide variable with the same name exists (declared outside of the function), the local variable will take precedence and shadow the script-wide variable inside that function. The consequence in your case is - tween
you used inside the function is not tween
you declared at the top of the script. So the latter stays uninitialized i.e. null.
https://gdscript.com/tutorials/variables/ (scroll down to "Variable Scope" section)
Think of the var declaration as defining where the variable lives. A file is a neighborhood, and the functions are houses. If the variable lives in a house, it can only be seen inside that house. If it lives outside of the house, then it can be seen from anywhere in the neighborhood.