我如何检测来自不同类的QGraphicsItem和QGraphicsPixmapItem图像之间的碰撞
How can I detect collision between QGraphicsItem and QGraphicsPixmapItem image from different classes
我有QGraphicsEllipse项目作为场景中的子弹。目标是QPixmap图像,我只想让子弹和图像相互作用,而不是目标对目标的碰撞。子弹是在场景类中创建的,QPixmaps是在对话框类中创建的。
我试着为QPixmaps添加一个QList,创建类似于QList QGraphicsItem *,但不认为编译器喜欢。任何建议都将不胜感激。
void Scene::advance()
{
QList <QGraphicsItem *> itemsToRemove;
foreach( QGraphicsItem * item, this->items())
{
if( !this->sceneRect().intersects(item->boundingRect()))
{
// The item is no longer in the scene rect, get ready to delete it
itemsToRemove.append(item);
}
}
foreach( QGraphicsItem * item, itemsToRemove )
{
this->removeItem(item);
delete(item);
}
QGraphicsScene::advance();
}
BoundRect包含在我的MainTarget类
QRectF MainTargets::boundingRect() const
{
qreal shift = 1;
return QRectF(-w/2 -shift, - h/2
- shift, w + shift, h + shift);
}
QPainterPath MainTargets::shape() const
{
QPainterPath path;
path.addRect(boundingRect());
return path;
}
编辑
class GraphicsCircle : public QGraphicsRectItem
// class for the pellets
{
public:
GraphicsCircle(qreal dirx, qreal diry)
: m_Speed(5)
, m_DirX(dirx)
, m_DirY(diry)
{
setRect(-3.0,-3.0,8.0,8.0);
setPos(-140, 195);
QRadialGradient rGrad( 0.0, 0.0, 20.0, 0.0, 0.0);
rGrad.setColorAt(0.0, QColor(255,255,255));
rGrad.setColorAt(0.7, QColor(255,255,225));
rGrad.setColorAt(1.0, QColor(255,0,0,0));
setBrush(QBrush(rGrad) );
setPen(QPen(Qt::NoPen));
}
virtual ~GraphicsCircle() {}
void advance(int phase)
{
if(phase == 0) return;
setPos(x()+m_Speed*m_DirX, y()+m_Speed*m_DirY);
}
private:
qreal m_Speed;
qreal m_DirX;
qreal m_DirY;
};
我把我的QPixmap对象改为QGraphicsPixmapItems。所以回到最初的问题,如何碰撞颗粒,QGraphicsItems,与目标,QGraphicsPixmapItems。我想应该是某种形式的:
if(pellets->collidesWithItem(targets){
remove(pellets)
remove(targets)
}
代替QPixmap,您可以使用QGraphicsPixmapItem并将图像添加到图形场景中。
此外,您正在调用QGraphicsScene矩形与项目的边界矩形相交,这是在其本地坐标空间:-
if( !this->sceneRect().intersects(item->boundingRect()))
因为它们在不同的坐标空间中,你需要在比较
之前将boundingRect转换为场景的坐标空间。QRectF sceneBoundingRect = item->mapToScene(item->boundingRect);
然后用这个来比较
if( !this->sceneRect().intersects(sceneBoundingRect))
相关文章:
- 将QGraphicsItem的移动区域限制在多边形区域内
- 如何在C++中正确引用来自不同类的类的对象?
- 是否可以创建一个从不同类调用函数的线程?
- C++不同类别的向量
- C 指针和对象作为不同类的一部分
- 有没有办法将指定不同类的 std::make_unique 传递到函数中
- 对具有相同方法的不同类使用一个变量
- 更改不同类的数组中的值
- 在工人类中使用不同类的静态函数进行实验
- 需要实例化不同类/对象并在启动时确定的硬件插槽的设计模式
- 如何更改 QGraphicsItem 对象的颜色?
- 不同类的向量
- 在C++中使用具有相同类的多个模板
- 组合的QGraphicsItem未检测到子项上的单击
- 如何生成派生同类对象的类
- 如何获得对不同类的引用,以便从所述类内部获得变量值
- 如何将QGraphicsItem QList保存到文件中,然后读取它?Qt c++
- 在基类方法中调用不同类的方法
- 模板化虚拟函数,管理单个类的不同类属性
- 我如何检测来自不同类的QGraphicsItem和QGraphicsPixmapItem图像之间的碰撞