move and collide -> wrong direction

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

hope u can help me…

The playerposition in script (kinematicbody2d)

func _physics_process(delta):
global.playerpos = self.get_global_position()

The (kinematicbody2d)

func _process(delta):
	if move == true:
		move_and_collide(Vector2(global.playerpos.x,global.playerpos.y) * delta)

The enemy is moving into the wrong direction (right bottom instead of the player position which is left bottom.

greets from germany

:bust_in_silhouette: Reply From: kidscancode

You’re using the player’s position vector as the enemy’s movement vector. That is incorrect. Also, you’re not normalizing the speed, so it’ll move inconsistently fast.

I suggest reading Tutorial: Vector Math.

If you want a vector pointing from the enemy to the player, use

var direction = (global_position - global.playerpos).normalized()

Then move using that vector

move_and_collide(direction * speed * delta)  # where speed is a float

A couple of other points:

  1. self is unnecessary
  2. get_global_position() can be simplified to the property: global_position
  3. No need to duplicate the player’s position in your global singleton. Give the enemy a reference to the player node and it can get that value directly.

Hello kidscancode,
thank you very very much.
After switching global_position and global.playerpos:

var direction = (global.playerpos - global_position).normalized()

everything is working fine.

Itention | 2019-07-11 18:18