PDA

View Full Version : Collision Detection between paintings????



mahsa
15th July 2012, 14:50
Hi

I have painted a big rectangle which surrounds a tiny push button , the push button moves to a new place where the mouse is clicked. but the problem is that I do not want this push button to come out of the big rectangle so I need collision detection which will help the pushbutton not to pass through the boundaries. becouse I'm new to Qt , I do not know what to do exactly. if some helps me about it I will be grateful.
here's my dialog.cpp code , I only have dialog.cpp and main.cpp ( this part works correct but I do not know what else I should do)
please tell me the source code for collision in this case
thanks


Dialog :: Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui:: Dialog)
{
ui->setupUi(this);

}
void Dialog :: paintEvent(QPaintEvent *e)
{
QPainter painter(this);
QRect rect(5,5,350,395);
QPen mypen(Qt::darkCyan);
mypen.setWidth(20);
painter.setPen(mypen);
painter.drawRect(rect);
}

void Dialog::mousePressEvent(QMouseEvent *event)
{
int _x_pos = event->pos().x();
int _y_pos = event->pos().y();
int _btn_pos_x = ui->pushButton->x() + ui->pushButton->width()/2;
int _btn_pos_y = ui->pushButton->y() + ui->pushButton->height()/2;
int offset = 40;
int start = _x_pos - offset;
int end = _x_pos + offset;
int begin = _y_pos - 10;
int finish = _y_pos + 10;
if( _btn_pos_x >= start && _btn_pos_x <= end ){
if( _y_pos < _btn_pos_y )
ui->pushButton->move(ui->pushButton->pos().x(), _btn_pos_y - 100);
else
ui->pushButton->move(ui->pushButton->pos().x(), _btn_pos_y + 100);
}

else if( _btn_pos_y >= begin && _btn_pos_y <= finish )
{
if( _x_pos > _btn_pos_x )
ui->pushButton->move(_btn_pos_x + 10,ui->pushButton->pos().y() );
else
ui->pushButton->move( _btn_pos_x /3 ,ui->pushButton->pos().y());

}
QDialog::mousePressEvent(event);
}

wysota
15th July 2012, 14:54
QRect::contains()

mahsa
16th July 2012, 06:47
I have 2 more questions:
1) in the discription of "bool QRect::contains ( const QPoint & point, bool proper = false ) const" what does PROPER mean?

2) what should I use for the collision of the smaller rectangle with a simple painted line?

thanks a lot for wasting ur time answering my silly questions:)

wysota
16th July 2012, 11:01
1) in the discription of "bool QRect::contains ( const QPoint & point, bool proper = false ) const" what does PROPER mean?

It's described in the docs: "If proper is true, this function only returns true if the given point is inside the rectangle (i.e., not on the edge)."


2) what should I use for the collision of the smaller rectangle with a simple painted line?
Use math to calculate intersection of a line with four sides of a rectangle. Alternatively convert the rect and line to painter paths and intersect those using QPainterPath API.