I can't turn the enemy around

Godot Version

4.3

Question

I need the enemy to turn towards the player but he doesn’t.

Script:

extends CharacterBody2D

var speed = 25
var player_chase = false
var player = null
var Global_player = self
@onready var animated_sprite_2d = $detection_area/AnimatedSprite2D

func _physics_process(_delta):
if player_chase:
position += (player.position - position)/speed

if (Global_player.global_position.x - global_position.x) < 0:
	animated_sprite_2d.flip_h = true
elif (Global_player.global_position.x - global_position.x) > 0:
	animated_sprite_2d.flip_h = false

func _on_detection_area_body_entered(_body):
player = _body
player_chase = true

func _on_detection_area_body_exited(_body):
player = null
player_chase = false

You are assigning:

var Global_player = self

and then you do this calculation:

Global_player.global_position.x - global_position.x

Global_player.global_position and global_position are exactly the same thing in this case, you’re basically doing this:

self.global_position.x - self.global_position.x

so the result of this calculation will always be 0, so your sprite will never flip.
If this script is on your enemy, then you should reference the player in the Global_player variable.

Nothing worked, he doesn’t turn around

What do you mean nothing worked? What did you try to do?
Please share your code/screenshots/everything that might be useful, otherwise it’s hard to help you.

I think you need to give him the player address instead of the global_player=self
like this:
@onready var targetplayer=$"../player"

and then this

if (targetplayer.position.x-position.x)<0:
		anim.flip_h=true
	else:
		anim.flip_h=false

anim is the animation

do not copy my script, you have to understand the code. as i said target is the player so send your player scene information in the code. and anim is the animated sprite.
@onready var anim=$AnimatedSprite2D

1 Like