Godot Version
4.7.2
Question
Recently I followed a tutorial to make the player’s camera bob up and down while they’re walking. I followed the code to the letter and it works, but there’s a yellow warning on a function near the bottom that applies the bobbing. I understand why the warning’s there, but I’m not sure on how exactly I fix it.
Here’s my code - the warning is on line 40, and reads “The local function parameter “bob_time” is shadowing an already-declared variable at line 11 in the current class.” Again, it works, but any advice on how to tweak it so the warning is gone would be appreciated. Thanks.
extends CharacterBody3D
var speed = 4.0
@export_group("bob")
@export var walk_speed = 4.0
@export var run_speed = 5.5
@export var bob_freq = 2.4
@export var bob_height = 0.08
var bob_time = 0
func _physics_process(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
# Change speed depending on if run input is active.
if Input.is_action_pressed("run") and is_on_floor():
speed = run_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 := (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 = move_toward(velocity.x, 0, speed)
velocity.z = move_toward(velocity.z, 0, speed)
move_and_slide()
# Bob the camera while moving.
bob_time += delta * velocity.length() * float(is_on_floor())
%Camera3D.transform.origin = bob(bob_time)
func bob(bob_time):
var bob_pos = Vector3.ZERO
bob_pos.y = sin(bob_time * bob_freq) * bob_height
return bob_pos