0 votes

So I'm new to this program and so far it's been really easy and fun to use it.
But I've encountered one problem. My character won't stop accelerating no matter the code i type to tell the thing to stop accelerating when it goes MAX_SPEED.
Here's my code so far

extends KinematicBody2D
const UP = Vector2(0, -1)
const GRAVITY = 20
const ACCELERATION = -10
const MAX_SPEED = 200
const JUMP_HEIGHT = -600

var motion = Vector2()

func _physics_process(delta):
    var friction = false
    motion.y += GRAVITY
    if Input.is_action_pressed("ui_left"):
        $Sprite.flip_h = true
        $Sprite.play("Run")
        motion.x = min(motion.x+ACCELERATION, MAX_SPEED)
    elif Input.is_action_pressed("ui_right"):
        $Sprite.flip_h = false
        $Sprite.play("Run")
        motion.x = max(motion.x-ACCELERATION, -MAX_SPEED)
    else:
        $Sprite.play("Idle")
        friction = true
    if is_on_floor():
        if friction == true:
            motion.x = lerp(motion.x, 0, 0.2)
        if Input.is_action_just_pressed("ui_up"):
            $Sprite.play("Jump")
            motion.y = JUMP_HEIGHT
    else:
        $Sprite.play("Jump")
        motion.x = lerp(motion.x, 0, 0.05)
    motion = move_and_slide(motion, UP)
    pass
in Engine by (32 points)

2 Answers

+1 vote
Best answer

Your ACCELERATION is negative (odd?).

So when you go left:

motion.x = min(motion.x+ACCELERATION, MAX_SPEED)

Will actually subtract to motion.x, and will always be lower than MAX_SPEED... in the negatives.


Your code also doesn't check for all potential cases of overshooting MAX_SPEED. Indeed, gravity can make you fall faster.

Maybe you could remove all caps from your current code and do them once just before calling move_and_slide:

motion.x = clamp(motion.x, -MAX_SPEED, MAX_SPEED)
motion.y = clamp(motion.y, -MAX_SPEED, MAX_SPEED)
motion = move_and_slide(motion, UP)
by (27,784 points)
selected by

Thank you so much! I really appreciate your time!

+1 vote

Hi,
i think you mixxed up your clamp function

if Input.is_action_pressed("ui_left"):
  $Sprite.flip_h = true
  $Sprite.play("Run")
  motion.x = min(motion.x+ACCELERATION, MAX_SPEED) # << -MAX_SPEED
elif Input.is_action_pressed("ui_right"):
  $Sprite.flip_h = false
  $Sprite.play("Run")
  motion.x = max(motion.x-ACCELERATION, -MAX_SPEED) # << MAX_SPEED

but did you know ... godot has a clamp function?

motion.x = clamp(motion.x,-MAX_SPEED,MAX_SPEED)
by (3,922 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.