Extending two child-classes with the same properties

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Ratty

Hi, more of an OOP question but it is specifically Godot I am trying to do this in.

I have StaticBody2D and RigidBody2D objects in my game, I want to extend both of these with some properties+methods common to both of them, do I have to make a child class for each or is there some way to just define the extension once and have it on both of them?

I experimented with extending the common parent of these (PhysicsBody2D) but then it was unable to find the methods unique to the child classes.

:bust_in_silhouette: Reply From: Inces

No, You can’t do it like this. Even if it was possible, some of the shared methods would become overriden.
You can either create two separate classes extending from them, or design a higher scope node, that will use StaticBody or RigidBody as child, and all the properties and methods will be written in higher scope, so You can only extend from one node. For example :

func physics_process() : 
        $childedbody.friction += 10
func ready() :
           $childedbody.connect(body_entered,self, on_child_body_enter)

whatever useful methods both Rigid and Static body share, while not coming from PhysicsBody… It is hard to imagine what could that be, except for signals :slight_smile:

Thanks. I suspected that was the case.
I’ll use two classes I think, they’ll be the same for now but I suspect there’s bound to be some differences later on.

Ratty | 2022-08-21 19:21