#[SOLVED] Keyword is question

8 messages · Page 1 of 1 (latest)

summer anvil
#

Hello everybody! I has the follow question with the code bellow:

if body is Mob or body is MobRage:

Are there some way more ellegant to compare a variable to a multiple class types instead re-rewrite in the example above?
I don't found it in godot documentation that information.

fleet moon
summer anvil
#

@fleet moon, my classes are independently one another, so MobRage isn't Mob. I know, the names are confusing...

fleet moon
#

Then I guess you could add all classes that you want to check to a group based on that use case. (https://docs.godotengine.org/en/stable/tutorials/scripting/groups.html)

Idk maybe you want to only hurt enemies with two legs, then you add them to the "two_legged" group (either in the editor or per code).

Then check like this:

if body.is_in_group("two_legged"):
#

Ok maybe to be more precise, it´s not the class that you add, but the node. So youd have to make sure the body node that you check for (Characterbody2D or another Physicsbody) is in that group

summer anvil
#

Tks, @fleet moon !

fleet moon
#

No problem! Hope that helps. Maybe there is another way, but that is just how id check for that (depending what you try to achieve in the end and hoping i understood you correctly).

~~In the end i wouldn't know how to get a list of classes to check against in a loop for example. ~~
Edit: Ok it is possible but it feels cursed:

# // Check if sprite is a Node, CharacterBody2D or Node2D
# // Returns true if it is any of those
var class_list = [Node, CharacterBody2D, Node2D]
func _ready() -> void:
    var sprite = Sprite2D.new()
    print(class_list.reduce(func(accum,element): return accum or is_instance_of(sprite,element))) 
        # // prints true since a Sprite2D is a Node and also a Node2D

You always could hard code the boolean check of course:

var is_valid_body_class = (
  body is Mob
  or body is MobRage
  or body is MobNotRage
  or body is ...
)
if is_valid_body_class:

That´s why groups came in mind to kind of "tag" nodes that have some similarity in a certain use case.

summer anvil
#

Amazing, @fleet moon, you got very well i needed. With that I can understand a couple ways more to solve a problem. I really thank you.