48 lines
1.5 KiB
GDScript
48 lines
1.5 KiB
GDScript
extends CharacterBody2D
|
|
|
|
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
|
|
|
|
const JUMP_VELOCITY = -300.0
|
|
const MAX_WALK_SPEED = 130.0
|
|
const ACCELERATION = 800.0 # Acceleration for smoother movement
|
|
const FRICTION = 600.0 # Deceleration when no input is given
|
|
|
|
var direction: float = 0
|
|
|
|
func _process(delta: float) -> void:
|
|
# Flip the sprite based on current direction
|
|
if direction != 0:
|
|
animated_sprite.flip_h = direction == -1
|
|
|
|
# Play animatinos
|
|
if not is_on_floor():
|
|
animated_sprite.play("jump")
|
|
elif direction != 0:
|
|
animated_sprite.play("run")
|
|
else:
|
|
animated_sprite.play("idle")
|
|
|
|
func _physics_process(delta: float) -> void:
|
|
# Add the gravity
|
|
if not is_on_floor():
|
|
velocity += get_gravity() * delta
|
|
|
|
# Handle jump30
|
|
if Input.is_action_just_pressed("jump") and is_on_floor():
|
|
velocity.y += JUMP_VELOCITY
|
|
|
|
# Get the input direction and handle the movement.
|
|
direction = Input.get_axis("move_left", "move_right")
|
|
if direction:
|
|
# Only apply more move acceleration if we're at/past max walk speed
|
|
# (only if accelerating towards opposite direction, or not yet at max speed)
|
|
#
|
|
# This implementation makes sure we don't accientaly decelerate by moving if we
|
|
# got velocity from something else (e.g. a boost), which the move_towards func
|
|
# would otherwise do.
|
|
if sign(velocity.x) != sign(direction) or abs(velocity.x) < MAX_WALK_SPEED:
|
|
velocity.x = move_toward(velocity.x, direction * MAX_WALK_SPEED, ACCELERATION * delta)
|
|
else:
|
|
velocity.x = move_toward(velocity.x, 0, FRICTION * delta)
|
|
|
|
move_and_slide()
|