I am not able to make friction work for my character in a 2d game. He seems to slide whenever he reaches the floor. Here is my code:

CODE:

``````extends KinematicBody2D

const UP = Vector2(0, -1)
const ACCELERATION = 50
const GRAVITY = 20
const MAX_SPEED = 200
const JUMP_HEIGHT = -500
var motion = Vector2()
var friction = false

func jumping():
if is_on_floor():
if Input.is_action_just_pressed("ui_up"):
motion.y = JUMP_HEIGHT

func friction():
if is_on_floor() and friction == true:
lerp(motion.x, 0.0, 0.2)
else:
if friction == true:
lerp(motion.x, 0.0, 0.1)

func move_right_left():
if Input.is_action_pressed("ui_right"):
motion.x = min(motion.x+ACCELERATION, MAX_SPEED)
\$Sprite.flip_h = false
\$Sprite.play("run")
elif Input.is_action_pressed("ui_left"):
motion.x = max(motion.x-ACCELERATION, -MAX_SPEED)
\$Sprite.flip_h = true
\$Sprite.play("run")
else:
if is_on_floor():
\$Sprite.play('idle')
else:
\$Sprite.play('jump')

func _physics_process(delta):
motion.y += GRAVITY
friction()
jumping()
move_right_left()
motion = move_and_slide(motion, UP)
``````
edited Feb 1

I edited your post to fix code formatting. In future, when you paste code, highlight it and click the "Code Sample" button (looks like "{}").

A `lerp`-call will only return a number, not assign that number to a variable! You have to take care of that yourself:

``````func friction():
if is_on_floor() and friction == true:
motion.x = lerp(motion.x, 0.0, 0.2)
else:
if friction == true:
motion.x = lerp(motion.x, 0.0, 0.1)
``````

Also don't forget to set `friction` back to `true` when testing this.

answered Feb 1 by (8,992 points)