AnimatedSprite2D flip sprite

Godot 4


I am new to Godot and I ran into a problem. I am trying to add a mob in my world scene that goes towards the player when the player is within the mobs area. I was able to make the mob go towards the player when the player is standing on the left side of the mob but it doesn’t work when you stand on the right side of the mob, it will walk away from player rather than go towards it. I attached the script for the mob.

extends CharacterBody2D

var SPEED = 50

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

var player

var chase = false

func _physics_process(delta):
	#Gravity for frog
	velocity.y += gravity * delta
	if chase == true:
		player = get_node("../../Player/Player")
		var direction = (player.position - self.position).normalized()
		velocity.x = direction.x * SPEED
		if direction.x > 0:
			get_node("AnimatedSprite2D").flip_h = true
			get_node("AnimatedSprite2D").flip_h = false
		velocity.x = 0	
func _on_player_detection_body_entered(body):
	if == "Player":
		chase = true
func _on_player_detection_body_exited(body):
	if == "Player":
		chase = false

try global_position instead

1 Like

Hi, did you mean global_position instead of (player.position - self.position)?

You could try sign(player.position.x - self.position.x) and set velocity.x = direction * SPEED

1 Like

var direction = (player.global_position - self.global_position).normalized()

1 Like

Thank you , that worked!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.