Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- position gdscript
- asked 14 hours ago in Engine by Feline-Biologist (28 points)
- edited 13 hours ago by Bojidar Marinov
- Answer Comment
- There, I fixed the code for you ;)
- commented 13 hours ago by Bojidar Marinov
- 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.
- answered 13 hours ago by Bojidar Marinov (798 points)
- selected 10 hours ago by Feline-Biologist
- Comment
- 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?
- commented 12 hours ago by Feline-Biologist
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement