+1 vote

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.

in Engine by (28 points)
edited by

There, I fixed the code for you ;)

1 Answer

+3 votes
Best answer

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.

by (1,608 points)
selected by

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?

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

It works now. Thank you!

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().

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.