user6285273
user6285273

Reputation:

Collision detection does not work properly

On the Screen, yellow ball is approaching to the yellow arc and hits it. Each arc (black, green and yellow are arcs - different objects). Collision detection when the ball hits yellow arcs shows 3 objects - 3 arcs, even when it hit only one yellow arc.

some code from Circles (arcs) (it inherits from QGraphicsItem). Width is a width of pen, so the collision is on the external border of arc.

#include ball.h

QRectF Circle::boundingRect() const
{
    QRectF rect( -radius, -radius, radius*2, radius*2);
    return rect;
}

QPainterPath Circle::shape() const
{
    QPainterPath path;
    path.addEllipse(QRectF( -radius-width, -radius-width, (radius+width)*2, (radius+width)*2));
    return path;
}

Some code from ball (it inheits from QGraphicsObject), and collision detection in paint().

QPainterPath Ball::shape() const
{
    QPainterPath path;
    path.addEllipse(boundingRect());
    return path;
}

QRectF Ball::boundingRect() const
{
    QRectF rect( -radius, -radius, radius*2, radius*2);
    return rect;
}

void Ball::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    if (!scene()->collidingItems(this).isEmpty()) {
        for (int y = 0; y<collidingItems().size(); y++)
            qDebug () << collidingItems().at(y);
        delete this;
    }
}

I probably know where is the mistake: in Circle::shape() the path is an ellipse, but it should be an arc. How am I supposed to make a path like this:

 painter->drawArc(boundingRect(), startAngle, spanAngle);

Upvotes: 0

Views: 167

Answers (1)

vcp
vcp

Reputation: 962

Are you sure about your bounding box calculation for arc?

QRectF Circle::boundingRect() const
{
    QRectF rect( -radius, -radius, radius*2, radius*2);
    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    return rect;
}

May be it should be :

QRectF( -radius-width, -radius-width, (radius+width)*2, (radius+width)*2));

I am unable to view the image, so I am guessing here. Just make sure that you are NOT calculating arc's bounding box bigger than what is really needed.

Upvotes: 1

Related Questions