0 votes
extends KinematicBody2D


var Player = null
var move = Vector2.ZERO
var speed = 500

func _physics_process(delta):
    move = Vector2.ZERO

    if Player != null:
        move = position.direction_to(Player.positon) * speed
    else:
        move = Vector2.ZERO

    move = move.normalized()
    move = move_and_collide(move)

func _on_Area2D_body_entered(body):
    if body != self:
        Player = body

func _on_Area2D_body_exited(body):
    Player = null
asked Jun 23 in Engine by jhale (20 points)
edited Jun 23 by kidscancode

1 Answer

+1 vote
Best answer

There are several things wrong with your movement code:

1) Don't normalize move(). That makes it very small and cancels out your speed.

2) Don't assign the returned value of move_and_collide() to move. The return from move_and_collide() is a KinematicCollision2D object.

3) Use delta in your movement: move_and_collide(move * delta)

If it still doesn't work, you may not be detecting the player. Put a print(body.name) in your body_entered callback and confirm that it's happening.

answered Jun 23 by kidscancode (17,130 points)
selected Jun 24 by jhale

I don't agree with 1):

normalizing should be done, but multiply with the speed AFTER the normalization.

I also think move_and_slide should be replaced with move_and_slide. Then no delta and assigning to move is correct.

Normalizing and multiplying by speed was already done. direction_to() returns a normalized vector. Doing it again is pointless.

oh, you are right. i confused direction_to and subtracting the vectors. sorry

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.