My character doesnt flip

Godot Version

Godot 4

Question

why is it not working?

My code:

extends CharacterBody2D

const SPEED = 300.0
const JUMP_VELOCITY = -400.0
@onready var sprite_2d = $Sprite2D

func _physics_process(delta):

if (velocity.x > 1 || velocity.x < -1)  :
	sprite_2d.animation = "running"
else:
	sprite_2d.animation = "default"
# Add the gravity.
if not is_on_floor():
	velocity.y += gravity * delta
	sprite_2d.animation = "jumping"

# Handle jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
	velocity.y = JUMP_VELOCITY

# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("ui_left", "ui_right")
if direction:
	velocity.x = direction * SPEED
else:
	velocity.x = move_toward(velocity.x, 0, SPEED)

move_and_slide()

var isLeft = velocity.x < 0
Sprite_2d.flip_h = isLeft

1 Like

That code:

var isLeft = velocity.x < 0
Sprite_2d.flip_h = isLeft

is never being called.

It should be in a function like _process() ← gets called every frame.
Then the code will be run every frame.
So it will check if the sprite should be flipped every frame.

Hope this helps :slight_smile:

can you make the code with that?

What do you mean?

can you write the code again with your solution?

extends CharacterBody2D

const SPEED = 300.0
const JUMP_VELOCITY = -400.0
@onready var sprite_2d = $Sprite2D

func _physics_process(delta):

    if (velocity.x > 1 || velocity.x < -1)  :
	sprite_2d.animation = "running"
    else:
	sprite_2d.animation = "default"
    # Add the gravity.
    if not is_on_floor():
	velocity.y += gravity * delta
	sprite_2d.animation = "jumping"

    # Handle jump.
    if Input.is_action_just_pressed("ui_accept") and is_on_floor():
	velocity.y = JUMP_VELOCITY

    # Get the input direction and handle the movement/deceleration.
    # As good practice, you should replace UI actions with custom gameplay actions.
    var direction = Input.get_axis("ui_left", "ui_right")
    if direction:
	velocity.x = direction * SPEED
    else:
	velocity.x = move_toward(velocity.x, 0, SPEED)

    # flipping code
    var isLeft = velocity.x < 0
    Sprite_2d.flip_h = isLeft

    move_and_slide()

In theory this should work :wink:

1 Like

thank you so much!!!

No problem :slight_smile:


What does this mean

Oh I thought this might happen.
You have to indent the code you want in the if statements

Sorry about that

what do you mean? Im a beginner

I think you need a tutorial for GDscript.

Then you will know what I mean.