The script is not working

Could you tell me what is wrong in these scripts and what needs to be fixed, since the player’s position is written in the output, but the mob does not go, also when you leave the zone once, he no longer sees you
1.
extends Node

var player_position = Vector2.ZERO

func _ready():
pass

func set_player_position(pos):
player_position = pos
2.
extends CharacterBody2D

var speed = 200

func _ready():
add_to_group(“Player”)
Global.set_player_position(position)

func _process(delta):
velocity = Vector2.ZERO

if Input.is_action_pressed("Left"):
	velocity.x -= 1  
if Input.is_action_pressed("Right"):
	velocity.x += 1 

velocity = velocity.normalized() * speed  

move_and_slide()  

extends Area2D

var speed : float = 100.0
var is_following : bool = false

func _on_body_entered(body):
if body.is_in_group(“Player”):
is_following = true
print(“Player entered the area.”)

func follow_player():
if is_following:
if Global.player_position:
var direction = (Global.player_position - global_position).normalized()
global_position += direction * speed * get_process_delta_time()
print("Following player at position: ", Global.player_position)
func _process(delta):
follow_player()

func _on_body_exited(body):
if body.is_in_group(“Player”):
is_following = false
print(“Player exited the area.”)

Global.set_player_position(position)

first i would like to encourage you to format your code appropriately using the preformatted text style
grafik
Right now it’s really hard to see the indentation of your code.

Secondly, I don’t understand which object the code belongs to
in your _ready() method, you wrote add_to_group("Player") which made me assume the Code is for the Player object.

but then I saw your _on_body_entered() method which is

func _on_body_entered(body):
   if body.is_in_group(“Player”):
      is_following = true
      print(“Player entered the area.”)

which means the player is able to see other players? Is a Mob also a player?

also when you leave the zone once, he no longer sees you

Isn’t your code designed to do exactly that?

func _on_body_exited(body):
   if body.is_in_group(“Player”):
      is_following = false
      print(“Player exited the area.”)

this means if a player leaves the area, is_following is set to false so the _process() completely stops working

1 Like