+1 vote

So this is my code. I wanna create a sprint, for example: when I press "shift", the speed of walk double or something like a speed bonus. Like a "walk to run" mechanic.

extends KinematicBody2D

const TARGET_FPS = 60
const ACCELERATION = 8
const MAX_SPEED = 64
const FRICTION = 10
const AIR_RESISTANCE = 1
const GRAVITY = 4
const JUMP_FORCE = 140

var motion = Vector2.ZERO

onready var sprite = $Sprite
onready var animationPlayer = $AnimationPlayer

func _physics_process(delta):
    var x_input = Input.get_action_strength("right") - Input.get_action_strength("left")

    if x_input != 0:
        animationPlayer.play("Walk")
        motion.x += x_input * ACCELERATION * delta * TARGET_FPS
        motion.x = clamp(motion.x, -MAX_SPEED, MAX_SPEED)
        sprite.flip_h = x_input < 0
    else:
        animationPlayer.play("Idle")

    motion.y += GRAVITY * delta * TARGET_FPS

    if is_on_floor():
        if x_input == 0:
            motion.x = lerp(motion.x, 0, FRICTION * delta)

        if Input.is_action_just_pressed("jump"):
            motion.y = -JUMP_FORCE
    else:
        animationPlayer.play("Jump")

        if Input.is_action_just_released("jump") and motion.y < -JUMP_FORCE/2:
            motion.y = -JUMP_FORCE/2

        if x_input == 0:
            motion.x = lerp(motion.x, 0, AIR_RESISTANCE * delta)

    motion = move_and_slide(motion, Vector2.UP)
Godot version Godot Engine v3.3.2.stable.official
in Engine by (13 points)

1 Answer

0 votes

It's actually easy. You just increase the acceleration and the maximum speed values when you want to sprint and reduce them back to normal after the sprint. Or you can increase just the maximum speed and add a value to motion.x to increase it or just multiply motion.x with a factor like 2 to double it after this line.

motion.x = clamp(motion.x, -MAX_SPEED, MAX_SPEED)

This way:

motion.x *= 2
by (1,051 points)

So, I've write this

if Input.is_action_pressed("sprint") and is_on_floor():
        motion.x *= 2

But when I press "right" and "left" together, he goes crazy, the character go out from the map.

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.