Godot Version
4.2.1
Question
I am new to godot and I am trying to make a 2D platformer. I am trying to make the character face the direction it is going but if I only flip the character it gets out of the collision shape. The CharacterBody2D is parent of an AnimatedSprite2D and a CollisionShape2D. I tried to search online but I couldn’t find a solution. Here is my character script:
extends CharacterBody2D
const SPEED = 400.0
const JUMP_VELOCITY = -900.0
@onready var animated_sprite_2d = $AnimatedSprite2D
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
func _physics_process(delta):
var move_right = int(Input.is_action_pressed("right"))
var move_left = int(Input.is_action_pressed("left"))
# Determine direction
if move_right > move_left:
scale.x = abs(scale.x)
elif move_left > move_right:
scale.x = -abs(scale.x)
# Determine animation
if (velocity.x > 1 || velocity.x < -1) and is_on_floor():
animated_sprite_2d.animation = "running"
else:
animated_sprite_2d.animation = "idle"
# Apply gravity
if not is_on_floor():
velocity.y += gravity * delta
animated_sprite_2d.animation = "jumping"
if velocity.y >= 0:
animated_sprite_2d.animation = "falling"
# Apply jump
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Determine speed based on direction
if move_right or move_left:
velocity.x = (move_right - move_left) * SPEED
else:
velocity.x = 0
move_and_slide()