Reputation: 11
The enemy in my game will not move towards the left when player is on the left but will move to the right. Then when the player is on the right the enemy will move to the player.
code for enemy:
extends KinematicBody2D
var run_speed = 100
var velocity = Vector2.ZERO
var collider = null
func _physics_process(delta):
velocity = Vector2.ZERO
if collider:
velocity = position.direction_to(collider.position) * run_speed
velocity = move_and_slide(velocity)
func _on_DetectRadius_body_entered(body):
collider = body
func _on_DetectRadius_body_exited(body):
collider = null
Upvotes: 1
Views: 950
Reputation: 40295
I suspect you are using an Area2D
and it is detecting something other than the player character. I remind you can use collision_mask
and collision_layer
to narrow what objects are detected. For example, are you sure the Area2D
is not detecting the enemy itself? For a quick check you can have Godot print the collider
to double check it is what you expect.
Furthermore, notice that wen an object leaves the Area2D
it will set collider
to null
regardless if there is still some object inside the Area2D
or not. I remind you that an alternative approach is using get_overlapping_bodies
.
And, of course, you can query each body
you get to see if it is the player character (for example by checking its node group, name, class, etc...). I go over filtering in more detail in another answer.
If you are getting the player character, there is another possible source of problems: position
vs global_position
. The code you have like this:
position.direction_to(collider.position)
Is correct if both the enemy and the collider
it got have the same parent. In that case their positions are in the same space. Otherwise, you may want to either work on global coordinates:
global_position.direction_to(collider.global_position)
Or you can bring the collider
position to local coordinates:
position.direction_to(to_local(collider.global_position))
And of course, double check that the Area2D
is positioned correctly. You can enable "Visible Collision Shapes" on the "Debug" menu, which will show it when running the game from the editor.
Upvotes: 0