Hello, I am trying to make enemy AI,
all of this in a script bound to the enemy scene
I used area2d node for that
this is the logic that detects the player
func _on_Area2D_body_entered(body):
if body.is_in_group("player"):
playerlocation.x = body.global_position.x - 5
playerdetected = true
print("playerdetected = True")
print(playerlocation)
func _on_Area2D_body_exited(body):
if body.is_in_group("player"):
playerdetected = false
print("playerdetected = false")
now what I tried to do is use the body.location to reference to player position but that does not update constantly
also the enemy scene never reaches the player location, instead the closer it gets the lower the speed until it reaches very small increments but never reaches the player "thats why I tried save body.location MINUS 5" just to make it lower so it can be reached but no fix.
so I tried this instead
onready var player = get_node("/root/main/Player") #reference to player in the scene
func _physics_process(delta):
#rotate lineofsight
#lineofsight.rotation += delta * 20 * PI
if playerdetected == true && playerlocation.x != global_position.x:
animations.animation = "walk"
directiontoplayer = transform.origin.direction_to(player.position)
velocity.y = 200*delta
if directiontoplayer.x > 0:
velocity.x = directiontoplayer.x/directiontoplayer.x * movespeed
$Node2D.scale.x = 1
elif directiontoplayer.x < 0:
velocity.x = -directiontoplayer.x/directiontoplayer.x * movespeed
$Node2D.scale.x = -1
velocity = move_and_slide(velocity, UP)
print(global_position.x)
#velocity.x = move_toward(velocity.x, movespeed.x*200, 500)
else:
animations.animation = "idle"
It worked just as intended but the limitation is that if I have multiple levels ie. scenes the same code will not work .. or is it? or is there another better way to do that?
that's my question..