Enemy following player problem

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By WanderingPanda84

I made a script for an enemy that follows the player. The script works, but when the player is under the enemy, the enemy sticks on to the player and the player can’t move. When the player touches the enemy from any other side this doesn’t happen.
Enemy script:

extends CharacterBody2D

var speed = 4000
var target = Node2D
var enemy = Node2D
var player_node = null

func _ready():
    player_node = get_node("/root/World/Player")

func _physics_process(delta):
    target = player_node.position
    enemy = self.position
    var direction = (target - enemy).normalized()
    velocity = direction * speed * delta


Player script:

extends CharacterBody2D

var speed = 400

func _physics_process(delta):
    var directionx = Input.get_axis("ui_left", "ui_right")
    if directionx:
	    velocity.x = directionx * speed
	    velocity.x = move_toward(velocity.x, 0, speed)
var directiony = Input.get_axis("ui_up", "ui_down")
if directiony:
	velocity.y = directiony * speed
	velocity.y = move_toward(velocity.y, 0, speed)

velocity = velocity.normalized()
velocity = velocity * speed

:bust_in_silhouette: Reply From: zapzoop0099

I was having the same problem, figured out that the motion for CharacterBody2D is set to 'Grounded ', set it to ‘Floating’ it will solve the problem.

You can change it by clicking on the Character Node and in the Inspector the first property is of the motion_mode, change it from “Grounded” to “Floating”

Hope this helps

1 Like