Can't flip a sprite in C#

Godot Version

4.21

Question

Just learning the engine and trying to flip the player sprite when it moves from left to right or vice versa. The game won’t run with this code, however. I might be missing something completely obvious, but I can’t figure it out for the life of me.

using Godot;
using System;

public partial class main_character : CharacterBody2D
{
	public const float Speed = 300.0f;
	public const float JumpVelocity = -400.0f;
	// Sprite variable for the main sprite
	@onready var animated_sprite_2d = $AnimatedSprite2D

	// Get the gravity from the project settings to be synced with RigidBody nodes.
	public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();

	public override void _PhysicsProcess(double delta)
	{
		Vector2 velocity = Velocity;

		// Add the gravity.
		if (!IsOnFloor())
			velocity.Y += gravity * (float)delta;

		// Handle Jump.
		if (Input.IsActionJustPressed("ui_accept") && IsOnFloor())
			velocity.Y = JumpVelocity;

		// Get the input direction and handle the movement/deceleration.
		// As good practice, you should replace UI actions with custom gameplay actions.
		Vector2 direction = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
		if (direction != Vector2.Zero)
		{
			velocity.X = direction.X * Speed;
		}
		else
		{
			velocity.X = Mathf.MoveToward(Velocity.X, 0, Speed);
		}
		
		Velocity = velocity;
		MoveAndSlide();
		bool isLeft = velocity.X < 0;
		animated_sprite_2d.flip_h = isLeft;
		
	}
}

Here are the problems:
image

Hi :slightly_smiling_face: You have multiple syntax errors in your class.

The following line is even an entire GDScript line.

@onready var animated_sprite_2d = $AnimatedSprite2D

In C#, you’d have something like below.

private AnimatedSprite2D _myAnimatedSprite2D;

public override void _Ready()
{
    _myAnimatedSprite2D = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
}

In addition, you are trying to access .flip_h, but in C# it’d be .FlipH.

More info about differences between the GDScript and C# APIs can be found at:

Thank you! One more thing: I attempted that, and was greeted by this error:
CS0266: Cannot implicitly convert type ‘Godot.Node’ to ‘Godot.AnimatedSprite2D’. An explicit conversion exists (are you missing a cast?) C:\Users\sunli\Documents\Godot Games\Learning\Platformer Retry\Scenes\main_character.cs(14,25)

My mistake, I edited the original answer to use GetNode<T>() instead of GetNode().

Thank you!

1 Like

Very quickly going to add this here, but if you’re planning to use C# with Godot, I VERY highly recommend setting up an IDE and not using the built in editor, as the IDE will tell you many of these issues and won’t even let you compile before you fix them. It’s a huge help! I can recommend this tutorial below which shows you two different ones and how to set them up with Godot!

1 Like