c++ - 如何检测对象来自哪个类? Qt

标签 c++ qt types detection

我在 QT 中用球编写物理模拟,这是我用来检测球之间碰撞的碰撞检测。

bool Ball:: circCollide(QList <QGraphicsItem *> items) {
    QPointF c1 = mapToScene( this->boundingRect().center());
//    qDebug() << "c1x" << c1.x();
//    qDebug() << "c1y" << c1.y();
//    qDebug() << "Listcount3: " << scene()->collidingItems(this).count();

    foreach (QGraphicsItem * t, items) {
//      qDebug() << "Classname: " << typeid(t).name();
//        if (typeid(t).name() == "Ball")
        if ( t->boundingRect().width()<200)
        {
            double distance = QLineF(c1,mapToScene( t->boundingRect().center())).length();
    //        qDebug() << "tx" << mapToScene(t->boundingRect().center()).x();
    //        qDebug() << "ty" << mapToScene (t->boundingRect().center()).y();
            double radius1 = this->boundingRect().width() / 2;
            double radius2 = t->boundingRect().width() / 2;
            double radii = radius1 + radius2;
    //        qDebug () << "distance radius1: " << radius1;
    //        qDebug () << "distance radius2: " << radius2;
    //        qDebug () << "distance :" << distance;
            if ( distance <= radii )
            {
            //    qDebug() << "true collision";
                return true;
            }
        }
    }
 //   qDebug() << "false collision";
    return false;
}

现在我遇到的问题是,当它们与我的墙壁发生碰撞时,有时也会调用此方法。 这些球有我自己制作并继承自 QGraphicsItem 的 Class Ball, 而墙壁的类 QLineF 也继承自 Qgraphicsitem。有什么好方法可以判断对象“t”是否属于 Ball 类? 我已经试过了

typeid(t).name() 

但是对于两个类 (P13QGraphicsItem) 返回相同的结果。

此外,我在开始时提供的列表包含与该项目碰撞的所有对象,因此我必须为其提供 QGraphicsItems 列表。

最佳答案

覆盖 QGraphicsItem::type在球。返回高于 UserType 值的内容,然后在每个 QGraphicsItem 上调用类型以确定它是否是一个 Ball

关于c++ - 如何检测对象来自哪个类? Qt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31999376/

相关文章:

c++ - 第二次运行时 while 循环中的 OPEN CV image.at<Vec3b>(b,a) 函数错误

c++ - 为什么 glGetProgramInfoLog 返回一个空字符串?

python - 如何将按钮添加到 QTreeView 行

qt - 同时在两个窗口中显示相机

qt - Qt5 和 Qt 4.8 中的模型和角色

python - 何时在 python 中应用(pd.to_numeric)和何时 astype(np.float64)?

c# - 通过反射查找给定/动态类型的 ObservableCollection

c++ - 如何转换为变量类型 - 在 C++ 中模拟类型变量

c++ - 重新定义访问修饰符有什么影响?

c++ - 为什么我得到 'vector subscript out of range' ?