Godot Version
4.3
Question
My character slides a little when walking diagonally when changing to the opposite direction, I have no clue what to do about it
extends CharacterBody2D
##Player constants =============================================================
var ACCELERATION = 800
var FRICTION = 2500
var MAX_SPEED = 300.0
##Player States ================================================================
enum {IDLE, WALK}
var _state = IDLE
##Player Nodes =================================================================
@onready var _animation_tree: AnimationTree = $AnimationTree
@onready var _state_machine = _animation_tree["parameters/playback"]
##Remember the last direction looking ==========================================
var _blend_position : Vector2 = Vector2.ZERO
##Define paths in the animation tree for idle and walk states ==================
var _blend_pos_path = [
"parameters/idle/idle_bs2D/blend_position",
"parameters/walk/walk_bs2D/blend_position"
]
var animTree_state_keys = [
"idle",
"walk"
]
func _physics_process(delta: float) -> void:
_move(delta)
_animate()
pass
##This function handles the player's movement. It checks if there's any input,
##applies friction if not, or moves the player and updates the blend position if
##there is input.
func _move(delta:float):
var input_vector = Input.get_vector("move_left","move_right","move_up","move_down")
##Not Moving ===============================================================
if input_vector == Vector2.ZERO:
_state = IDLE
_apply_friction(FRICTION * delta)
else:
_state = WALK
_apply_movement(input_vector * ACCELERATION * delta)
_blend_position = input_vector
move_and_slide()
##This function reduces the player's velocity based on the friction value,
##eventually stopping the player if the velocity is small enough.
func _apply_friction(amount) -> void:
if velocity.length() > amount:
velocity -= velocity.normalized() * amount
else:
velocity = Vector2.ZERO
##This function increases the player's velocity based on the input and limits
##it to the maximum speed.
func _apply_movement(amount) -> void:
velocity += amount
velocity = velocity.limit_length(MAX_SPEED)
##This function updates the player's animation based on the current state and
##blend position.
func _animate()->void:
_state_machine.travel(animTree_state_keys[_state])
_animation_tree.set(_blend_pos_path[_state], _blend_position)
pass