Adding accessors for inherited members

Parantres-Parantres- Posts: 4Member

How can I write a getter for a node member which is inherited from its parent? When I try to redeclare the member with setget it complains that the member already exists.

extends Sprite

var position setget set_position ,get_position

gives me the error The member "position" already exist in a parent class

Node2D already has the set_position method as setter for position, and I tried to override it in the child, but it doesn't seem to get called when changing the member.

Comments

  • MegalomaniakMegalomaniak Posts: 2,739Admin

    So the above code is attached to the parent only, or did you try to attach it also to the child?

  • TwistedTwiglegTwistedTwigleg Posts: 2,814Admin
    edited July 27

    I'm not sure you can override non virtual C++ functions in GDScript, which may be part of the issue. You may need to change the name from position to something that isn't already defined in Godot's C++ code, like custom_position for example.

    Edit: Also, welcome to the forums! :smile:

  • Parantres-Parantres- Posts: 4Member

    Thank you TwistedTwigleg. :)

    I think the issue is a tension between the setget syntax and the fact that you can't redeclare an inherited member variable. According to the documentation, setget has to come directly after the declaration, but I can't redeclare the variable in the child node. Just writing position setget _set_position gives an error as expected.

    I don't know whether there are deeper reasons why you can't add accessors to an inherited variable or this is just something that can't be expressed with the current syntax.

    If I used a different variable name it wouldn't give me the desired behavior. :) I want the accessor to be called when the sprite moves around.

    @Megalomaniak said:
    So the above code is attached to the parent only, or did you try to attach it also to the child?

    The code is attached to the sprite node. The variables are inherited from an ancestor, I believe Node2D.

  • TwistedTwiglegTwistedTwigleg Posts: 2,814Admin

    You can detect if the node has moved through the _notification function (documentation). I believe the notification is something like NOTIFICATION_TANSFORM_CHANGED. Then whenever that signal is received, you can call your position setter.

  • Parantres-Parantres- Posts: 4Member

    Actually, I didn't say it right. It's more general than the sprite just moving around. I want to translate tile coordinates to pixel coordinates when I set the position and translate them back when I get it. The most elegant solution for this is with a setter/getter.

    For now I'm just calling these functions manually, but if it's possible I'd prefer to access the property via the the functions.

Leave a Comment

BoldItalicStrikethroughOrdered listUnordered list
Emoji
Image
Align leftAlign centerAlign rightToggle HTML viewToggle full pageToggle lights
Drop image/file