0 votes

At the minute I have a simple 2D setup. There is a function called in _process() to handle inputs. If it detects a jump key, I use apply_central_impulse() to make the rigidbody move upwards and fall as normal, and this works fine. I want to make it so that pressing right, for example, makes the character move right. The problem is, I don't want to apply a force, because the movement is slow at first as it accelerates. The character should move at a speed when pressed, and not move at all when the key is not held. How do I achieve this? The docs warn against directly changing the velocity of a rigidbody directly.

in Engine by (273 points)

1 Answer

0 votes
by (4,084 points)

I have tried something like this:

func _process(delta):

func manage_inputs():
    var moving = false
    if Input.is_action_just_pressed("ui_up"):
        if linear_velocity.y == 0:
    if Input.is_action_pressed("ui_right"):
        moving = true
    if Input.is_action_pressed("ui_left"):
        moving = true
    if !moving:
        vel_linear.x = 0

func jump():
    apply_central_impulse(Vector2(0, -1000))

func move(direction):
    if direction == "right":
        vel_linear.x = 400
    if direction == "left":
        vel_linear.x = -400

func _integrate_forces(state):
    state.linear_velocity.x = vel_linear.x

But doing things in this way causes the character to sporadically freeze when moving continuously. What's up with that? Are there any alternative solutions?

i've just tested it ... runs fine by me. Must be something else. Perhaps the surface the body glides on?

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 Frequently asked questions and 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 [email protected] with your username.