0 votes

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:


extends KinematicBody2D

const UP = Vector2(0, -1)
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)
        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
    elif Input.is_action_pressed("ui_left"):
        motion.x = max(motion.x-ACCELERATION, -MAX_SPEED)
        $Sprite.flip_h = true
        if is_on_floor():

func _physics_process(delta):
    motion.y += GRAVITY
    motion = move_and_slide(motion, UP)
in Engine by (12 points)
edited by

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

1 Answer

0 votes

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)
        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.

by (10,327 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.