|
|
|
|
Reply From: |
kidscancode |
When the Player scene is instanced in Main, it becomes part of the tree and you treat it like any other node. To get the player’s position you would use
$Player.position
or
get_node("Player").position
Both are equivalent, $<node_name>
is a shorthand for using get_node()
.
I’m aware of the get_node() and $… But how can I get the value of the ship values from INSIDE the enemy scene? Both are not in the same scene.
What I want is something like this (at the “enemy” scene):
func _process(delta):
if playerposition (variables and/or attributes at the "ship" scene) < enemy.position:
enemy.position -= 10 * delta
if playerposition (variables and/or attributes at the "ship" scene) > enemy.position:
enemy.position += 10 * delta
My question is how to get the attributes inside the “ship” scene from inside the “enemy” scene.
Leandro | 2018-11-28 17:08
Actually, they’re all in the same scene - Main. At runtime, there is only one scene. It really doesn’t matter whether the nodes in it are instances or not. So if your main scene looks like this:
Main
-- Player
-- Enemy
Then there are many different ways to pass the information. A couple of examples:
- From the Enemy, use
get_node("../Player").position
- From Main, pass the player’s position to the Enemy:
$Enemy.target_position = $Player.position
- When the enemy is instanced, give it a reference to the player:
$Enemy.target = $Player
, then you can reference it in the enemy script whenever you need it.
Pros/cons:
- This is simple, but less optimal. It is usually a bad idea to hardcode the tree hierarchy in the script, as it will break if you move things around.
- In this scenario, you’d have to continually update that variable from main.
- This is probably the best option. Since the enemy has a reference to the player, you can have it respond to more than just position. Perhaps it does something if the player’s health is low, or if the player has a powerup, etc.
kidscancode | 2018-11-28 17:18
- When the enemy is instanced, give it a reference to the player:
$Enemy.target = $Player, then you can reference it in the enemy script
whenever you need it.
Thanks… Where can I get more information about this reference stuff?
Leandro | 2018-11-28 17:42
By “reference”, I mean you can refer to it. If the Enemy’s target
variable points to the Player node, then any time you like in the Enemy script you can do things like:
if position.distance_to(target.position) < 10:
# do something
You can reference any property or function of the Player using target.<name>
By the way, have you gone through the official tutorial? A lot of this kind of thing is covered in the Step By Step section.
kidscancode | 2018-11-28 18:01
Mea culpa. There’s a lot I still did not see from the official tutorial. I’ll check it now.
Thanks!
Leandro | 2018-11-28 23:51