# How can I code a "sprint" on my 2D platform game?

Attention Topic was automatically imported from the old Question2Answer platform.

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

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

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
``````

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.

Xicola | 2021-06-07 13:03

you can create sprint like this, I have created it successfully :
My script for movement:

``````extends KinematicBody2D

const ACCELERATION = 800
const FRICTION = 800
export var MAX_SPEED = 50
export var sprinting_speed = 50

var velocity = Vector2.ZERO

func _physics_process(delta):
var input = Vector2.ZERO

input.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
input.y = Input.get_action_strength("move_down") - Input.get_action_strength("move_up")

if input != Vector2.ZERO:
velocity = velocity.move_toward(input * MAX_SPEED, ACCELERATION * delta)
else:
velocity = velocity.move_toward(Vector2.ZERO, FRICTION * delta)

if Input.is_action_just_pressed("is_sprinting"):
MAX_SPEED += sprinting_speed

if Input.is_action_just_released("is_sprinting"):
MAX_SPEED = 50

velocity = move_and_slide(velocity)

``````

Savage_Reaper | 2022-12-20 11:18

Isn’t MAX_SPEED a constant? How are you adding something to it?

magicalogic | 2022-12-21 18:10