我在 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/