Invalid type in function "apply_knockback" in base "Node2D (gun.gd)". Cannot convert argument 1 from Callable to Vector2

Godot Version

4.3.Stable

Code

extends Node2D

var can_shoot : bool = true
var knockback: Vector2 = Vector2.ZERO
var knockback_timer: float = 0.0

const BULLET = preload(“res://Scenes/bullet.tscn”)

@onready var muzzle: Marker2D = $Marker2D
@onready var gun_cooldown: Timer = $GunCooldown
@onready var randomized: AudioStreamPlayer = $Randomized

func _process(_delta: float) → void:
look_at(get_global_mouse_position())

rotation_degrees = wrap(rotation_degrees, 0, 360)
if rotation_degrees > 90 and rotation_degrees < 270:
	scale.y = -1
else:
	scale.y = 1

if Input.is_action_just_pressed("fire") and can_shoot:
	shoot()

func shoot() → void:

# Cooldown
can_shoot = false
$GunCooldown.start()

# Spawn bullet
var bullet_instance = BULLET.instantiate()
get_tree().root.add_child(bullet_instance)
bullet_instance.global_position = muzzle.global_position
bullet_instance.rotation = rotation
 
# Sound
$Randomized.play_with_random_pitch()

# Knockback
var knockback_direction = (global_position - global_position).normalized
apply_knockback(knockback_direction, 150.0, 0.12)

func apply_knockback(direction: Vector2, force: float, knockback_duration: float) → void:
knockback = direction * force
knockback_timer = knockback_duration

func _on_gun_cooldown_timeout() → void:
can_shoot = true

Question

I dont really understand the error, can someone help me?

Hi,

That line:

var knockback_direction = (global_position - global_position).normalized

should be:

var knockback_direction = (global_position - global_position).normalized()

with parenthesis at the end.

That’s a tricky one, but basically, using normalized without parenthesis will refer to the function itself (which is a “Callable”, as written in the error message), whereas using normalized() with parenthesis will actually call the function and get its result, here a Vector2.


A thing you could do is specify the type of your variable, like this:

var knockback_direction: Vector2 = (global_position - global_position).normalized()

By doing that, you’ll have an error before even launching the game if you forget the parenthesis. Not specifying the type can be great, but can lead to some issues like the one you just had.
That would look like this:
image

This fixed the error but now my knockback isnt working

You’re assigning two values, knockback and knockback_timer but never using them afterward.

In _process, you could add something like this:

if knockback_timer > 0:
    knockback_timer -= delta
    global_position += knockback * delta

I did not test the code, I’ve just written it on the fly to give you an idea. You may need to adjust it. Feel free to open another topic if you’re struggling with the knockback itself :slight_smile:

It didnt work but i opened a new topic about the knockback

1 Like