Smooth movement without gravity

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By soulldev

The player in my game moves in all directions (UP, DOWN, LEFT, RIGHT), but the movement is too clattered (it’s not smooth at all), to make it more smooth i’m looking to apply an acceleration when the player moves, and when the player stops.

i’m still a beginner, i don’t have any idea how to do that…

:bust_in_silhouette: Reply From: kidscancode

Acceleration/deceleration means you want the velocity to smoothly ramp up (to the maximum) or down (to 0). This can be done with Vector2.linear_interpolate()

You didn’t mention what kind of body your player is, but this concept can be adapted to other types of movement. friction and acceleration should be values between 0 and 1.

extends KinematicBody2D

var speed = 300
var friction = 0.05
var acceleration = 0.1
var velocity = Vector2.ZERO

func _physics_process(delta):
	var input_velocity = Vector2.ZERO
	# Check input for "desired" velocity
	if Input.is_action_pressed("ui_right"):
		input_velocity.x += 1
	if Input.is_action_pressed("ui_left"):
		input_velocity.x -= 1
	if Input.is_action_pressed("ui_down"):
		input_velocity.y += 1
	if Input.is_action_pressed("ui_up"):
		input_velocity.y -= 1
	input_velocity = input_velocity.normalized() * speed

	# If there's input, accelerate to the input velocity
	if input_velocity.length() > 0:
		velocity = velocity.linear_interpolate(input_velocity, acceleration)
	else:
		# If there's no input, slow down to (0, 0)
		velocity = velocity.linear_interpolate(Vector2.ZERO, friction)
	velocity = move_and_slide(velocity)

If you’re unfamiliar with the concept of linear interpolation, I’ve written a small guide.

Great answer, pure and simple.

Human1428 | 2019-10-02 21:27

Hi
I tried this in a top down context and really liked the result. I’ like to know how to adapt this to a 2d sidescroller but only for the x axis without affecting the movement in the y axis.
Thanks

Osamu | 2020-04-13 02:46

Wonderfull, thanks for this!

MaxDeveloper | 2020-06-23 17:23

thanks a lot for this

Shlopynoobnoob | 2020-10-05 17:23

My dum-dum brain tried to use clamp() to go back to 0
but now, i know the answer: ༼ つ ◕_◕ ༽つ INTERPOLATE

GodotFan69 | 2021-03-16 00:53

Great answer but note that the fiction and acceleration here will be bound to the frame rate

dekajoo | 2023-03-25 12:56