Help with Managing Visibility in Code

Godot 4.2.2

I need help with managing the visibility of my Sprites in code so I can deactivate the visibility of them here’s my code:

extends CharacterBody2D

const SPEED = 200
const FAST_SPEED = 400
var current_speed = SPEED
var animation_player : AnimationPlayer

var animation_speed = NORMAL_ANIMATION_SPEED

func _ready():
	var animation_player = $AnimationPlayer

func _physics_process(delta):

	var motion = Vector2.ZERO
	if Input.is_action_pressed("d"):
		%Run.flip_h = false
		motion.x += 1
	elif Input.is_action_pressed("a"):
		%Run.flip_h = true
		motion.x -= 1
	elif Input.is_action_pressed("s"):
		motion.y += 1
	elif Input.is_action_pressed("w"):
		motion.y -= 1

	motion = motion.normalized()

	if Input.is_key_pressed(KEY_SHIFT):
		current_speed = FAST_SPEED
		animation_speed = FAST_ANIMATION_SPEED
		current_speed = SPEED
		animation_speed = NORMAL_ANIMATION_SPEED

	position += motion * current_speed * delta

Where I want to manage the visibility is right before an animation plays!

You can change visibility in the animation player, try that first!


@gertkeno will that work like for if I wanted it to only show it when the player is not interacting with any keys?

That’s why I mainly chose to change it within the script

If it works for the AnimationPlayer then it will work for visibility properties

Also @gertkeno does it work with Spritesheets/Frames?

If the property exists, especially in the inspector, it can be animation player’d

Hmmm. Could you also show me how to change it within the script, If Possible?

Edit the visible property of each sprite, I know from other posts you have $Run and $Idle but that information is not present in this post.

elif Input.is_action_pressed("w"):
	motion.y -= 1
	$Run.visible = true
	$Idle.visible = false
	$Run.visible = false
	$Idle.visible = true

If you hover your mouse over the property in the inspector it will tell you the name of the property in the script, it may be surprising, but usually it’s lowercase and underscores instead of spaces.

It worked! Thank you so much!

Hi!!! This is very easy. You can use the method get_node(NodePath node_path) and set parameter Visible or (in GDScript) visible true or false. If is true, your sprite will became visible and vice versa.
Sample code:
extends CharacterBody2D
@onready var sprite = get_node(“MySprite”)

func _ready():

func _physics_process(delta):
if(Input.IsActionPressed(“Left Button Mouse”)
sprite.visible = true
if(Input.IsActionPressed(“Left Button Mouse2"”)
sprite.visible = false
Actually, I don’t quite understand what you need. If my method is not suitable for your task, then please tell me more about it.

1 Like