Saturday, November 5, 2022
HomeGame Developmentc++ - Object::cast_to in godot nonetheless casts even when the forged is...

c++ – Object::cast_to in godot nonetheless casts even when the forged is invalid


I’ve a category for a projectile outlined like this:

namespace godot
{

class Projectile : public RigidBody2D
{
    // Godot construction
personal:
    GDCLASS(Projectile, RigidBody2D);

public:
    digital void _physics_process(double delta) override;

    Projectile();
    ~Projectile();

};
}

Then I’ve a category for something that may be shot:

class ShootableObject : public RigidBody2D
{
    // Godot construction
personal:
    GDCLASS(ShootableObject, RigidBody2D);

public:
    digital bool receiveDamage(double injury);
    
    ShootableObject();
    ~ShootableObject();

};

That is how I register them with the engine:

#embody "Projectile.h"
#embody "ShootableObject.h"

void initialize_example_module(godot::ModuleInitializationLevel p_level)
{
    if (p_level != godot::MODULE_INITIALIZATION_LEVEL_SCENE)
    {
        return;
    }
    godot::ClassDB::register_class<godot::Projectile>();
    godot::ClassDB::register_class<godot::ShootableObject>();
}

Then for collisions, I do that within the projectile class:

void Projectile::_physics_process(double delta)
{
  TypedArray<Node2D> colliders = get_colliding_bodies();
  bool hit = false;
  for (int i=0; i<colliders.dimension(); ++i)
  {
    Object* o = colliders[i];

    if (PhysicsBody2D* physique = Object::cast_to<PhysicsBody2D>(o))
    {
      if (ShootableObject* shootable = Object::cast_to<ShootableObject>(physique))
      {
        if(shootable->is_inside_tree())
          shootable->receiveDamage(props.injury);
      }
      hit = true;
    }
  }

  if (hit)
  {
    queue_free();
  }
}

The issue is, the cast_to all the time returns a pointer, even when two projectiles hit one another. That subsequently causes crash when making an attempt to name receiveDamage on one thing that’s not ShootableObject.

I can keep away from the difficulty by doing this, however that is simply plain silly:

        if (body->get_class() != "ShootableObject")
        {
          return;
        }

Why is that this taking place? I attempted to allow RTTI in my construct in case there was an issue with that (should not be) and that didn’t assist. Is there one thing incorrect with these class definitions?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments