godot 4.3
I was trying to make a momentum for a platformer but character will accel too fast and decel to fast Preformatted text
extends CharacterBody2D
@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
const MAX_SPEED = 200.0
const JUMP_VELOCITY = -230.0
#Jump counts
var jump_count = 0
var max_jumps = 2
var SPEED = 0.0
var acc = 2.5
var lastDirection: float
var Friction = 8
func get_input():
var direction = Input.get_axis(“Left”, “Right”)
calculate_speed(direction)
lastDirection = direction
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, Friction * SPEED)
func _physics_process(delta: float) → void:
if not is_on_floor():
velocity += get_gravity() * delta
if Input.is_action_just_pressed("ui_accept") and jump_count < max_jumps:
velocity.y = JUMP_VELOCITY
jump_count += 1
if is_on_floor():
jump_count = 0
_set_animation()
move_and_slide()
get_input()
func _set_animation() → void:
if velocity.x < 0: animated_sprite_2d.flip_h = true
elif velocity.x > 0: animated_sprite_2d.flip_h = false
if velocity: animated_sprite_2d.play("move")
func calculate_speed(direction: float) → void:
if lastDirection == direction: SPEED += acc
else: SPEED = 0
if SPEED < 0:
SPEED = 0
if SPEED > MAX_SPEED: SPEED = MAX_SPEED