Advertisement
otorp2

enemy fly to player

Mar 31st, 2016
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. 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)
  2.  
  3. I have this as the enemy's process code:
  4.  
  5. func _process(delta):
  6. var pos_player = preload("../player.scn").instance().get_pos()
  7. var pos_self = get_pos()
  8. var dir_player = (pos_self - pos_player).normalized()
  9. pos_self += dir_player * SPEED * delta
  10. set_pos(pos_self)
  11. Theoratically should this work yet it doesn't. It just makes the enemy fly down vertically.
  12.  
  13. position gdscript
  14. asked 14 hours ago in Engine by Feline-Biologist (28 points)
  15. edited 13 hours ago by Bojidar Marinov
  16. Answer Comment
  17. There, I fixed the code for you ;)
  18.  
  19. commented 13 hours ago by Bojidar Marinov
  20.  
  21. 1 Answer
  22.  
  23. +3
  24. votes
  25. Best answer
  26. 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.
  27.  
  28. E.g, If you have the following node structure:
  29.  
  30. level
  31. player
  32. enemy (script here!)
  33. then you can use
  34.  
  35. var player_pos = get_node("../player").get_pos()
  36. to get the player node.
  37.  
  38. answered 13 hours ago by Bojidar Marinov (798 points)
  39. selected 10 hours ago by Feline-Biologist
  40. Comment
  41. 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?
  42.  
  43. commented 12 hours ago by Feline-Biologist
  44.  
  45. 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).
  46. 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).
  47. 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