Godot v4
I want to know why I’m getting this error: Invalid operands ‘float’ and ‘Nil’ in operator ‘*’.
I’ve been following multiple tutorials on creating movement for my game, I’m new to this and don’t really understand what I could do to fix this error, my game immediately closes, and I get the error notification every time I run it. I’ve looked and looked but I can’t find anything that even helps me a little on finding a fix.
The error happens at line : velocity.x = lerp(velocity.x, direction.x * speed, delta * 1.0)
My Full Code:
extends CharacterBody3D
var speed
const WALK_SPEED = 5.0
const SPRINT_SPEED = 8.0
const CROUCH_SPEED = 3.0
const JUMP_VELOCITY = 4.8
const SENSITIVITY = 0.004
const BOB_FREQ = 2.4
const BOB_AMP = 0.08
var t_bob = 0.0
const BASE_FOV = 75.0
const FOV_CHANGE = 0.5
var gravity = 9.8
var crouching_depth = -0.5
var lerp_speed = 10.0
@onready var head = $Head
@onready var camera = $Head/Camera3D
@onready var stand_collision = $Stand_collision
@onready var crouch_collision = $Crouch_collision
@onready var ray_cast_3d = $RayCast3D
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):
if not is_on_floor():
velocity.y -= gravity * delta
if Input.is_action_just_pressed("Jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
if Input.is_action_pressed("Crouch"):
speed = CROUCH_SPEED
head.position.y = lerp(head.position.y, 0.444 + crouching_depth, delta * lerp_speed)
crouch_collision.disabled = true
stand_collision.disabled = false
elif !ray_cast_3d.is_colliding():
crouch_collision.disabled = false
stand_collision.disabled = true
head.position.y = lerp(head.position.y, 0.444 + crouching_depth, delta * lerp_speed)
if Input.is_action_pressed("Sprint"):
speed = SPRINT_SPEED
else:
speed = WALK_SPEED
var input_dir = Input.get_vector("Left", "Right", "Up", "Down")
var direction = (head.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 * 4.0)
velocity.z = lerp(velocity.z, direction.z * speed, delta * 4.0)
else:
velocity.x = lerp(velocity.x, direction.x * speed, delta * 1.0)
velocity.z = lerp(velocity.z, direction.z * speed, delta * 1.0)
t_bob += delta * velocity.length() * float(is_on_floor())
camera.transform.origin = _headbob(t_bob)
var velocity_clamped = clamp(velocity.length(), 0.5, SPRINT_SPEED * 2)
var target_fov = BASE_FOV + FOV_CHANGE * velocity_clamped
camera.fov = lerp(camera.fov, target_fov, delta * 8.0)
move_and_slide()
func _headbob(time) → Vector3:
var pos = Vector3.ZERO
pos.y = sin(time * BOB_FREQ) * BOB_AMP
pos.x = cos(time * BOB_FREQ / 2) * BOB_AMP
return pos