Reputation: 41
I'm programming a physicssimulation in QT with balls and this is the collision detection I'm using to detect collision between balls.
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;
}
Now I have the problem that this sometimes is also called for when they collide with my walls. The balls have the Class Ball which I made myself and inherits from QGraphicsItem, while the walls have the class QLineF which also inherits from Qgraphicsitem. Is there any good way to figure out whether an object "t" belongs to the class Ball? I've already tried
typeid(t).name()
but that returns the same for both classes (P13QGraphicsItem).
Also the list I feed to at the beginning contains all objects colliding with this item hence I have to feed it a list of QGraphicsItems.
Upvotes: 0
Views: 1809
Reputation: 1966
If Ball
is derived from QObject
, and has the Q_OBJECT
macro in its declaration, you can simply call QObject::metaObject
and QMetaObject::className
:
t->metaObject()->className();
Upvotes: 1
Reputation: 5067
You can try casting similar to this example:
Tag* tag = new Tag();
Polygon* polygon = new Polygon();
Polygon* polygon_cast = dynamic_cast<Polygon*>(polygon);
if(polygon_cast) qDebug() << "Cool!";
else qDebug() << "oh..";
Tag* tag_cast = dynamic_cast<Tag*>(tag);
if(tag_cast) qDebug() << "Cool!";
else qDebug() << "oh..";
Upvotes: -1
Reputation: 650
Override QGraphicsItem::type
in Ball. Return something above the value of UserType
and then call type on each QGraphicsItem
to determine if it is a Ball
.
Upvotes: 2