Godot Version
4.7.2.stable
Question
im currently trying to make a 3d platformer with an accelerating and decelerating character, when the character is in the air and the player does not press any buttons, the character freezes in the air, i know that this is caused by my coded in acceleration and friction lines, how can i fix them?
extends CharacterBody3D
@onready var metal = %thing
var SPEED = 100
const JUMP_VELOCITY = 50
var accel = 3
var friction = 5
@onready var spring_arm = $"SpringArm3D"
var movement_vector := Vector3.ZERO
var _last_movement_direction := Vector3.BACK
@onready var anim = $CollisionShape3D/thing/AnimationPlayer2
func _ready():
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
func _physics_process(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta * 8
# Handle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
if velocity.y < 0:
anim.play("air")
if velocity.y > 0:
anim.play("jump")
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var input := Input.get_vector("forward", "back", "right", "left")
var direction = Vector3(input.x, 0, input.y).rotated(Vector3.UP, spring_arm.rotation.y)
if input:
anim.play("fly")
else:
anim.play("idle")
if direction:
accelerate(direction)
else:
apply_friction()
move_and_slide()
if direction.length() > 0.2:
_last_movement_direction = direction
var target_angle := Vector3.BACK.signed_angle_to(_last_movement_direction, Vector3.UP)
metal.global_rotation.y = target_angle + 80.1
func accelerate(direction: Vector3):
velocity = velocity.move_toward(SPEED * direction, accel)
func apply_friction():
velocity = velocity.move_toward(Vector3.ZERO, friction)