niklas2902 / py4godot

Python scripting for Godot. This GDExtension plugin allows you to use Python like GDScript, accessing the Godot engine's features and benefiting from Python's vast ecosystem.
MIT License
62 stars 7 forks source link

How to reference other nodes? #70

Open svntax opened 1 month ago

svntax commented 1 month ago

How do you work with references to other nodes from within a Python script? For example, I have a script for an enemy that will follow a Node2D target, and for testing purposes, here is how I have it set up to print the target node's position:

from py4godot.classes import gdclass
from py4godot.classes.core import NodePath
from py4godot.classes.CharacterBody2D.CharacterBody2D import CharacterBody2D
from py4godot.classes.Node2D.Node2D import Node2D

@gdclass
class Enemy(CharacterBody2D):
    speed: float = 4.0
    target_node_path: NodePath

    def _ready(self) -> None:
        self.target_node = self.get_node(self.target_node_path)
        print(self.target_node.position)

But self.get_node() returns a Node, so as a result, I can't access the position and get this error:

AttributeError: 'py4godot.classes.Node.Node.Node' object has no attribute 'position'

Is there a way to get the node type from get_node()? Or is there another way to access other nodes?

niklas2902 commented 1 month ago

Hey, I'm sorry. I didn't document this properly. I implemented some functions for casting. If your node is also a Node2D, changing the line to:

self.target_node = Node2D.cast(self.get_node(self.target_node_path))

should fix the issue. If you have any other problems, feel free to ask.

svntax commented 1 month ago

Thank you! That fixes the problem for me.