Godot Version
Godot 4
Question
I want to make it so when you hold down the shift button, you start building up speed like Pizza Tower where you would build up speed and start smashing enemies. How can I make it so that you start to accelerate when you hold the shift key?
Here’s the code for the CharacterBody3D I’m using:
extends CharacterBody3D
var speed
var acceleration
const WALK_SPEED = 10.0
const SPRINT_SPEED = 20.0
const JUMP_VELOCITY = 7.8
const max_velocity = 100.0
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = 18.8
@onready var camera = $Camera3D
func _ready():
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
camera.current = true
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventMouseButton:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
elif event.is_action_pressed("ui_cancel"):
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
if event is InputEventMouseMotion:
rotate_y(-event.relative.x * 0.005)
camera.rotate_x(-event.relative.y * 0.005)
camera.rotation.x = clamp(camera.rotation.x, -PI/4, PI/3)
func _physics_process(delta):
if not is_on_floor():
velocity.y -= gravity * delta
# Handle Jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Handle Sprint.
if Input.is_action_pressed("sprint"):
speed= SPRINT_SPEED
else:
speed = WALK_SPEED
# Get the input direction and handle the movement/deceleration.
var input_dir = Input.get_vector("left", "right", "forward", "backward")
var direction = (camera.transform.basis * transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
if is_on_floor():
if direction:
velocity.x = direction.x * speed
velocity.z = direction.z * speed
else:
velocity.x = lerp(velocity.x, direction.x * speed, delta * 7.0)
velocity.z = lerp(velocity.z, direction.z * speed, delta * 7.0)
else:
velocity.x = lerp(velocity.x, direction.x * speed, delta * 3.0)
velocity.z = lerp(velocity.z, direction.z * speed, delta * 3.0)
move_and_slide()```