How to make an RigidBody2D fly to a different RigidBody2D?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Feline-Biologist
:warning: Old Version Published before Godot 3 was released.

Let’s say I have two RigidBody2D’s. One player and one enemy. I want to make the enemy fly to the player(for testing purposes)

I have this as the enemy’s process code:

func _process(delta):
	var pos_player = preload("../player.scn").instance().get_pos()
	var pos_self = get_pos()
	var dir_player = (pos_self - pos_player).normalized()
	pos_self += dir_player * SPEED * delta
	set_pos(pos_self)

Theoratically should this work yet it doesn’t. It just makes the enemy fly down vertically.

There, I fixed the code for you :wink:

Bojidar Marinov | 2016-03-31 09:01

:bust_in_silhouette: Reply From: Bojidar Marinov

The problem is that you are instancing the player every frame from scratch. This mean that all you aren’t looking at the same player, you are looking at another instance of the player (and also, it is highly inefficient that way :-)). What you should do is use get_node(...) to get the node of the player, and then use get_pos on that.

E.g, If you have the following node structure:

level
    player
    enemy (script here!)

then you can use

var player_pos = get_node("../player").get_pos()

to get the player node.

How should that work with scenes then? Because I currently have seperate scenes for the player character, level, parallax background and the enemy. Should I instance the player scene into the enemy scene?

Feline-Biologist | 2016-03-31 09:46

Maybe you should read tutorial step by step to better understanding nodes, scenes and instancing. Anyway you should instance player and enemy into level (in editor or via script).
Note that in your code you even did not add player as a child node of your scene. You are just making an instance of player in every frame, and then you read its position (position of root node in player scene i guess).
Finally, if you want enemy fly to a player the direction should be pos_player - pos_self

lukas | 2016-03-31 10:31

It works now. Thank you!

Feline-Biologist | 2016-03-31 11:47

I’ve had problems with set_pos() with RigidBody2D because it behaves like teleporting.

Some of the problems are:

  • if RigidBody2D are inside a area2d you sometimes doesn’t get exit
    event when use set_pos() with new position outside of area
    (godot think RigidBody2D is still inside the area “no enter event on same area”)
  • set_pos() not a physical movement

If you want use physical behaviors while moving use set_linear_velocity() or apply_impulse() inside _fixed_process().

puppetmaster- | 2016-04-01 09:29