Qt如何使用偏移量将项目添加到场景中?

时间:2014-04-16 01:31:20

标签: c++ qt trigonometry

我将QGraphicsItem(项目符号)添加到一行的基础。 advance方法将项目移动到项目中,使其看起来好像来自线尖。添加碰撞后,这不起作用。有没有办法在setPos(x,y)值中添加偏移量,使其显示在行的顶端而不是基线。

此外,该线以360度角旋转,因此需要转换为线指向的位置。

//function that adds item to base of line created

    qreal dirx = m_FireTarget1.x()+140;
    qreal diry = m_FireTarget1.y()-195;


    qreal length = sqrt(dirx*dirx+diry*diry);
    if (length!=0)
    {
        // normalized direction vector
        qreal invLength= 1.0/length;
        dirx *= invLength;
        diry *= invLength;

        // creating an angle perturbation of +/- 3°
        qreal alphaPerturbation = static_cast<qreal>(qrand()%6-3) * M_PI / 180.0;
        qreal xPerturbation = cos(alphaPerturbation);
        qreal yPerturbation = sin(alphaPerturbation);

        dirx = dirx*xPerturbation - diry*yPerturbation;

        diry = diry*xPerturbation + dirx*yPerturbation;

        GraphicsCircle * circle = new GraphicsCircle(dirx, diry, -140, 195);
        addItem(circle);

-140,195是创建线的基础。好像我已经做了你所说的我相信的事情。

1 个答案:

答案 0 :(得分:1)

让我们说你的广告系列有一定的degreeAngle,你想要将子弹移动到该方向的某个distance,你必须这样做:

// cos and sin functions get radians angle as argument so you must convert it
radiansAngle = degreeAngle * PI / 180;
offsetX = distance * cos(radiansAngle);
offsetY = distance * sin(radiansAngle);

在您的情况下,这转换为:

qreal radiansAngle = line.angle() * M_PI / 180;
qreal offsetX = line.length() * cos(radiansAngle);
qreal offsetY = line.length() * sin(radiansAngle);

所以你的新职位是旧职位加上抵消:

qreal newX = -140 + offsetX;
qreal newY =  195 + offsetY;

然后我很抱歉,但我无法理解你如何将参数传递给GraphicsCircle构造函数,但如果GraphicsCircle * circle = new GraphicsCircle(dirx, diry, -140, 195);将圆圈放到坐标(-140,195),那么你应该使用......

GraphicsCircle * circle = new GraphicsCircle(dirx, diry, newX, newY);
addItem(circle);

...将其放置到新坐标。