I am using godot 4
Question
So I have written a script to move my 2d character.
while everything works fine but there is a problem.
when the character jumps and when I click the left arrow , for a moment the animation/frame for left animation plays but when I release the left arrow key the animation/frame for right jump plays. How to fix this ?
Here is the script I wrote.
extends CharacterBody2D
const SPEED = 200.0
const JUMP_VELOCITY = -500.0
@onready var sprite_2d = $Sprite2D
var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)
func _physics_process(delta):
#Animations:
if(velocity.x>1):
sprite_2d.animation=“running_right”
elif(velocity.x<-1) :
sprite_2d.animation=“running_left”
else:
sprite_2d.animation=“default”
# Add the gravity.
if not is_on_floor():
if velocity.x<0:
sprite_2d.animation="jumping_left"
else:
sprite_2d.animation="jumping"
velocity.y+=gravity*delta
# 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()