The wrong chase

I have a problem when I enter the area2d of the mob, it just runs forward all the way to the border, and does not follow the player (unfortunately I cannot show the video since I am a new user).Help me solve this problem

extends CharacterBody2D
const SPEED = 300.0
var player = null
func _physics_process(delta) → void:*
if not player:
velocity = Vector2.ZERO
return

var direction = (self.transform.origin - player.transform.origin).normalized()
velocity = direction * SPEED
move_and_slide()

func _on_detector_body_entered(body: Node2D) → void:
if body.is_in_group(“Player”):
player = body

try to use this. Both works the same way
var direction = ( player.global_position - global_position ).normalized()

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

use this one here.

extends CharacterBody2D
const SPEED = 300.0
var player = null
func _physics_process(delta) → void:*
if not player:
velocity = Vector2.ZERO
return

move_and_slide()

func _on_detector_body_entered(body: Node2D) → void:
if body.is_in_group(“Player”):
var direction = ( player.global_position - global_position ).normalized()
velocity = direction * SPEED

what I did here is too only move the character when mob detect it and stop it when player is not in range.

I checked your code, but I got a mistake: var direction= (player.global_position - global position).normalized() - incorrect access to the global_position property or key for the base object of type “Nil”

share the screenshot of error with full code

Can you try this?

extends CharacterBody2D
const SPEED = 300.0
var player = null
func _physics_process(delta) → void:*
if not player:
velocity = Vector2.ZERO
return

var direction = (player.global_position - global_position).normalized()
velocity = direction * SPEED
move_and_slide()

func _on_detector_body_entered(body: Node2D) → void:
if body.is_in_group(“Player”):
player = body

I tried, but the mob flies up and in the wrong direction relative to the player

actually you try to get player position in slime_green script directly. This will not work in this case. You need to create a signal in player script and connect it with your slime_green script and then you can access the player.global_position.

Other Solution : is used global script and create a variable in it name player_position or whatever you like and then use this player position in your green_slime script to access player position in this case the code look like this
(Global.player_position - global_position).normalized()

make sure in global script you create the player position variable like
var player_position

and assign the value in player script like this
Global.player_position = global_position

1 Like