Enemy going backwards instead of following player

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

I’m trying to make this work from few hours. The code is right there are no errors when I start the game its 2d game.the enemy zombie is kinematic

func _process(delta):
var speed = 30
var zombiPos = get_global_position()
var heroPos = hero.get_global_position()
var direction = (get_global_position() - hero.get_global_position()).normalized()
move_and_collide(direction * speed * delta)
 hero.get_global_position() - get_global_position()

Deli | 2022-01-25 01:59

:bust_in_silhouette: Reply From: DaddyMonster

The trick with minusing coordinates is to always do target position minus character position. That’s to say, if you want the vector starting at vector A and going to vector B then it’s B-A

If you imagine vector as arrows, then it’s the tip of the arrow minus the nock of the arrow.

So it’s:

var direction = (hero.get_global_position()-get_global_position()).normalized()
:bust_in_silhouette: Reply From: ponponyaya

To find a vector pointing from A to B use B - A.

Like following:

var direction = (hero.get_global_position() - get_global_position()).normalized()

You can take a look at Godot Doc.

Hehe, we posted almost identical answers within seconds of each other. I was first! :wink:

DaddyMonster | 2022-01-25 00:58

Yes, what a coincidence! :slight_smile:

ponponyaya | 2022-01-25 01:07

thanks guys :wink: now it’s working fine. I thought it wouldn’t matter if I write A - B seems like I must learn vector math

cvetirodrigez | 2022-01-26 11:18

Welcome. It helps if you think about standard numbers as 1d vectors (on a number line like in primary school). 5-7 is not the same as 7-5. In 2d you can grab a pen and paper and add two vectors by drawing them head to tail on a graph. A+B and B+A hit the same endpoint but take a different route. If you think about it, that’s true in 1d (and 3d) as well. Take a few minutes to do this and you’ll see intuitively what it means to add and minus vectors.

DaddyMonster | 2022-01-26 11:58