How do i code a sprint?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dandevuni

Its hard to find how to sprint code and i dont know how to do it,not in 3d,but sprinting in 2d,help

maybe increase your move speed, when you click sprinting button?
example :
if event.is_action_pressed("R_click"): move_speed = 200

potatobanana | 2021-03-01 12:59

Did that,but for some reason the animation didnt work

Dandevuni | 2021-03-03 07:09

:bust_in_silhouette: Reply From: bloodsign

if you don’t want to make that big of change to your current code base, assuming you have:

var velocity = Vector2.ZERO
var acceleration = 10

func _physics_process(delta):
 if Input.is_action_pressed("right"):
  velocity.x += acceleration 
 velocity = move_and_slide(velocity)

For your movement code, you could simply add:

var speed_bonus = 0

func _physics_process(delta):
 if Input.is_action_pressed("right"):
  velocity.x += acceleration + speed_bonus

 if Input.is_action_pressed("shift_run"):
  speed_bonus = 10
  speed_bonus = 0
 velocity = move_and_slide(velocity)

Well it worked but,the animation didnt,whenever i tried to move the player,the animation just froze amd doesmt animate,it worked if i use it for anything else but it just doesnt work whenever i tried to use the sprint code

Dandevuni | 2021-03-03 07:08

1 Like

Hello, i know it might be a little late to respond to this topic, but for those who may be looking to solve the same problem here is a possible solution:

extends myNode

#stp01 - Speed variables
export var speed			:	float =  10.0
export var sprintSpeed		:	float =  10.0

func _physics_process(delta):

#stp02 - Usual moviment lines

var dir = Vector3.ZERO
	if Input.is_action_pressed("ui_right"):
		dir.x += 1
	if Input.is_action_pressed("ui_left"):
		dir.x -= 1
	if Input.is_action_pressed("ui_backward"):
		dir.z += 1
	if Input.is_action_pressed("ui_foward"):
		dir.z -= 1
	if Input.is_action_pressed("ui_up"):
		dir.y += 1
	if Input.is_action_pressed("ui_down"):
		dir.y -= 1

#stp03 - Applying the velocities to the vector

	if Input.is_action_pressed("ui_sprint"):
		dir = dir * (speed + sprintSpeed)
		dir = dir * (speed)

#stp04 - Applying dir values to the object vector

	translate_object_local(dir / 100)

Basically that’s it. You need to configure the UI buttons, of course. The speed value is “applied” near the end (stp03), with the sprint being just another value that is added in the multiplication.