I want to change a variable from a script using another one

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

I have a variable that keeps track of which direction my player is facing. I want this variable to be at a different default values depending of the current level being played.
For example,in Level 1 he faces left by default,but I might want him to face right in Level 2.

Here’s what I tried to do:

extends Node2D

func _ready():
    var facing_x = $KinematicBody2D.get("facing_x")
    facing_x = -1

This is the node of the game’s level,in case the information is relevant.

:bust_in_silhouette: Reply From: p7f

Hi, actually, get will only give you the value of that variable. Modifying it wont do anything to the original variable.

you should try something like

extends Node2D

func _ready():
    $KinematicBody2D.facing_x = -1
:bust_in_silhouette: Reply From: gioele

Your variable is defined in your player script that extends a KinematicBody2D, right?

I think you should access it by simply using dot notation.
eg:

onready var player = $Player_node
func _ready():
    var facing_x = player.facing_x  #copy value from node
    ...
    facing_x = -1 #change variable in function
    player.facing_x = -1 #change value in node

If you change facing_x by assigning a new value, it happens only locally (within the _ready function but does not apply to the actual Player node).

Anyway if you only need to change the sprite you could simply use flip_h().

Thank you very much,this solved the problem.

I have a variable that keeps track of what direction the player is facing not only to set animations,but also because I intend to add a dash feature to my game,and want it to happen in the direction the player is currently facing,so flip_h wouldn’t be enough.

Harmonikinesis | 2020-08-27 14:54