0

I am trying to extract collision coordinate between two rectangles moving inside a QGraphicsScene and send these coordinates to a QLineEdit. Basically the position of the rectangle when they collide. I was reading this source and this source. They advice to use QGraphicsItem::collidesWithPath but no success.

This is the snipped of code that does the collision with my own implementation:

MyItem::MyItem()
{
    angle = (qrand() % 360);
    setRotation(angle);
    speed = 5;
    int startX = 0;
    int startY = 0;
    if((qrand() % 1)){
        startX = (qrand() % 200);
        startY = (qrand() % 200);
    }else{
        startX = (qrand() % -100);
        startY = (qrand() % -100);
    }
    setPos(mapToParent(startX, startY));
}

void MyItem::paint(QPainter *painter,
                   const QStyleOptionGraphicsItem *option,
                   QWidget *widget)
{
    QRectF rec = boundingRect();
    QBrush brush(Qt::gray);
    if(scene()->collidingItems(this).isEmpty()){
        brush.setColor(Qt::green); // no collision
    }else{
        brush.setColor(Qt::red);  // yes collision
        doCollision();
    }
    painter->fillRect(rec, brush);
    painter->drawRect(rec);
}

void MyItem::advance(int phase)
{
    if(!phase) return;
    QPointF location = this->pos();
    setPos(mapToParent(0, -(speed)));
}

void MyItem::doCollision()
{
    if((qrand() %1)) {
        setRotation(rotation() + (180+(qrand() % 10)));
    }else{
        setRotation(rotation() + (180+(qrand() % -10)));
    }
    // see if the new position is in bounds
    QPointF newPoint = mapToParent(-(boundingRect().width()), -(boundingRect().width() + 2));
    if(!scene()->sceneRect().contains((newPoint))){
        newPoint = mapToParent(0, 0); // move it back in bounds
    }else{
        setPos(newPoint); // set new position
    }
}

How to extract collision coordinates (x,y) between objects in QGraphicsScene and send the coordinates (x,y) to QLineEdit? Thanks for shedding light on this issue.

  • What coordinates do you mean? you mean the position of the rectangle when they collide (the position of the rectangle is the center of the rectangle) or is it another position? – eyllanesc Feb 24 '19 at 01:22
  • yes the position of the rectangle when they collide –  Feb 24 '19 at 03:19
  • Hello eyllanesc, I edited the question adding that specific part that wasn't clear. Thanks for your comment. –  Feb 24 '19 at 16:22

0 Answers0