Issues coding my enemy's Player Detection for attacking.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Carthrolas

For some reason it crashes my game when my character gets into range for my enemy to attack. It has no problem detecting the player, but I keep getting this error that states…

Invalid type in function ‘get_angle_to’ in base ‘KinematicBody2D (Elite.gd)’. Cannot convert argument 1 from Nil to Vector2.

I’ve listed portions relevant to this script below. I hope someone can help!

func Attack():
can_fire = false
speed = 0
fire_direction = (get_angle_to(player_position)/3.14)*180
get_node(“TurnAxis”).rotation = get_angle_to(player_position)
var skill = load(“res://Enemyranged.tscn”)
var skill_instance = skill.instance()
skill_instance.skill_name = “Enemyranged”
skill_instance.fire_direction = fire_direction
skill_instance.rotation = get_angle_to(player_position)
skill_instance.position = get_node(“TurnAxis/CastPoint”).get_global_mouse_position()
skill_instance.origin = “Enemy”
get_parent().add_child(skill_instance)
yield(get_tree().create_timer(0.6), “timeout”)
can_fire = true
speed = 0

func _on_Area2D_body_entered(body):
if body == player:
player_in_range = true
state = “Attack”
print("You’re in range: ", player_in_range)

func _on_Area2D_body_exited(body):
if body == player:
player_in_range = false
state = “Stand”
print("You’re out of range: ", player_in_range)

func Sight_Check():
if player_in_range == true:
var space_state = get_world_2d().direct_space_state
var sight_check = space_state.intersect_ray(position, player.position, [self], collision_mask)
if sight_check:
if sight_check.collider.name == “Camera”:
player_in_sight = true
player_position = player.get_global_position(“Camera”)
state = “Attack”
else:
player_in_sight = false
state = “Stand”

Is Attack() being called before SightCheck? Then player_position will not be set.

Use the code tag for better code.

larrxi | 2020-11-19 02:05

:bust_in_silhouette: Reply From: jgodfrey

From the error, it seems that your player_position variable is null when your Attack function is called (at least on this particular call).