Posted December 04, 2024 by KLAY_69420
#This script controls the player character's movement, animations, and interactions.
extends CharacterBody2D
#The script inherits from CharacterBody2D, which is designed
#for 2D characters in Godot. It has built-in physics functions like move_and_slide.
#cosntants
const SPEED = 400.0 #Speed at which the chartacter mover horizontally
const JUMP_VELOCITY = -900.0 #Upward velocity
@onready var sprite_2d: AnimatedSprite2D = $Sprite2D
#This function runs every frame and handles movement, animations, and gravity.
func _physics_process(delta: float) -> void:
#If the character is moving horizontally (velocity.x > 1 or < -1), the "running" animation plays.
if (velocity.x > 1 || velocity.x < -1):
sprite_2d.animation = "running"
else:
#Otherwise, it defaults to the "idle" animation.
sprite_2d.animation = "default"
#Adds gravity when the character is not on the ground using get_gravity().
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
#If the "jump" action is pressed and the character is on the floor,
# it applies JUMP_VELOCITY to the vertical velocity.
# Handle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# creating the animation for jumping
sprite_2d.animation = "jumping"
# 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("left", "right")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 12, SPEED)
move_and_slide()
#The horizontal direction is determined by the "left" and "right" inputs.
#If no direction is pressed, it decelerates toward 0 for smoother stopping.
var isLeft = velocity.x < 0
sprite_2d.flip_h = isLeft
#Based on the movement direction (velocity.x), the sprite flips horizontally (flip_h).