0 votes

I'm having trouble with a an enemy trying to follow the player only on the x-axis. The problem is that i have set up collisons on a platform so that the enemy doesnt fall off the edge and n collison changes direction and movement to stimulate a "patroling" effect. When i call the Area2d signal "bodyentered" the enemy changes its direction to the player, but when it hits the wall it changes its direction again and stops following the player as he is still in the area2d range, so the bodyentered signal isnt called again.
Here's my enemy code:

func _physics_process(delta):
if direction == "left" :
    velocity.x = -SPEED*delta
elif direction == "right":  
    velocity.x = SPEED*delta
velocity.y += GRAVITY*delta
if is_on_floor():
    velocity.y = 0;
velocity = move_and_slide(velocity, FLOOR)

func ChangeDirection():
if direction == "right":
    #get_node( "Sprite" ).set_flip_h( false )
    sprite.set_scale(scaling)
    direction = "right"
elif direction == "left":
    #get_node( "Spr1ite" ).set_flip_h( true )
    sprite.set_scale(Vector2(scaling.x*-1,scaling.y))
    direction = "left"



#Damage Calculation
func take_damage(damage):
HEALTH -= damage
print(HEALTH)

Reverse direction and movement

func _on_LeftReverse_body_entered(body):
ChangeDirection()
direction = "right"
pass


func _on_RightReverse_body_entered(body):
ChangeDirection()
direction = "left"
pass


func _on_DetectPlayer_body_entered(body):

if body.is_in_group("Player"):
    if player.get_position().x < get_position().x:
        direction = "right"
    elif player.get_position().x > get_position().x:
        direction = "left"
in Engine by (16 points)

1 Answer

0 votes

Hi, with your code a quick solution would be to set a bool variable like

func _on_DetectPlayer_body_entered(body):
chasing = true
if body.is_in_group("Player"):
    if player.get_position().x < get_position().x:
        direction = "right"
    elif player.get_position().x > get_position().x:
        direction = "left"


func _on_DetectPlayer_body_exited(body):
chasing = false

and place

 if chasing  == true:
 return

at the begining of your function detecting collision with wall. So you avoid your object to change dierction when hitting a wall

by (288 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.