Godot Version 4.2.2
Cant figure out what to do. I want it so when my player walks on the ground a footstep sound plays. This is my script for my player.
extends CharacterBody3D
const NORMAL_SPEED = 3.5
const RUN_SPEED = 5
var speed = NORMAL_SPEED
const JUMP_VELOCITY = 3
const SENSITIVITY = 0.003
# Bob variables
const BOB_FREQ = 1.8
const BOB_AMP = 0.02
var t_bob = 0.0
# fotstep variables
var can_play : bool = true
signal step
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = 9.0
@onready var head = $Head
@onready var camera = $Head/Camera3D
func _ready():
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _unhandled_input(event):
if event is InputEventMouseMotion:
head.rotate_y(-event.relative.x * SENSITIVITY)
camera.rotate_x(-event.relative.y * SENSITIVITY)
camera.rotation.x = clamp(camera.rotation.x, deg_to_rad(-40), deg_to_rad(60))
func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y -= gravity * delta
# Handle jump.
if Input.is_action_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Check for run input.
if Input.is_action_pressed("run"):
speed = RUN_SPEED
else:
speed = NORMAL_SPEED
# Get the input direction and handle the movement/deceleration.
var input_dir = Input.get_vector("left", "right", "front", "back")
var direction = (head.transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
if direction:
velocity.x = direction.x * speed
velocity.z = direction.z * speed
else:
velocity.x = 0.0
velocity.z = 0.0
# Head bob
t_bob += delta * velocity.length() * float(is_on_floor())
camera.transform.origin = _headbob(t_bob)
move_and_slide()
func _headbob(time) -> Vector3:
var pos = Vector3.ZERO
pos.y = sin(time * BOB_FREQ) * BOB_AMP
return pos