Godot Version
4.2.1
Question
Hello, so I recently started learning how to program and wanted to learn while making a game. Godot seemed like a good place to start. After a few tutorials and a little help from the internet I tried making a 2d platformer. Now I wanted to add a sprint function while a different animation is played when sprinting. It does not seem to work. I already tried searching the web for help but did not find anything.
Here is my code an the Sprint function is at the bottom.
extends CharacterBody2D
const NORMAL_SPEED = 200.0
const SPRINT_SPEED = 800.0
const JUMP_VELOCITY = -500.0
@onready var sprite_2d = $Sprite2D
Jump count
var jump_count = 0
var max_jumps = 2
Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)
func _physics_process(delta):
# Animations
if (velocity.x > 1 || velocity.x <-1):
sprite_2d.animation = “Walk”
else:
sprite_2d.animation = “Idle”
# Add the gravity.
if not is_on_floor():
velocity.y += gravity * delta
sprite_2d.animation = "Jump"
if is_on_floor():
jump_count = 0
# Handle jump.
if Input.is_action_just_pressed("jump") and jump_count < max_jumps:
velocity.y = JUMP_VELOCITY
jump_count +=1
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("left", "right")
if direction:
velocity.x = direction * NORMAL_SPEED
else:
velocity.x = move_toward(velocity.x, 0, 30)
move_and_slide()
var isLeft = velocity.x <0
sprite_2d.flip_h = isLeft
func _unhandled_input(event):
var direction = 0 # Initialize direction variable
if Input.is_action_pressed("right"):
direction += 1
if Input.is_action_pressed("left"):
direction -= 1
if Input.is_action_pressed("sprint"):
if velocity.x > 1 || velocity.x < -1:
sprite_2d.animation = "Run"
velocity.x = direction * SPRINT_SPEED # Adjust speed during sprint
else:
if velocity.x > 1 || velocity.x < -1:
sprite_2d.animation = "Walk"
velocity.x = direction * NORMAL_SPEED # Set back to normal speed
else:
sprite_2d.animation = "Idle"