C++ Qt如何向具有偏移的场景添加项目?
我将QGraphicsItem(项目符号)添加到一行的底部。“前进”方法将项目移动到项目中,使其看起来好像来自行的顶端。添加碰撞后,这不起作用。是否有方法将偏移量添加到setPos(x,y)值,使其显示在线的尖端而不是底部 此外,直线以360度角旋转,因此需要平移到直线所指向的位置C++ Qt如何向具有偏移的场景添加项目?,c++,qt,trigonometry,C++,Qt,Trigonometry,我将QGraphicsItem(项目符号)添加到一行的底部。“前进”方法将项目移动到项目中,使其看起来好像来自行的顶端。添加碰撞后,这不起作用。是否有方法将偏移量添加到setPos(x,y)值,使其显示在线的尖端而不是底部 此外,直线以360度角旋转,因此需要平移到直线所指向的位置 //function that adds item to base of line created qreal dirx = m_FireTarget1.x()+140; qreal diry =
//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);
//将项添加到已创建行的底端的函数
qreal dirx=m_FireTarget1.x()+140;
qreal diry=m_FireTarget1.y()-195;
qreal length=sqrt(dirx*dirx+diry*diry);
如果(长度!=0)
{
//归一化方向向量
qreal invLength=1.0/长度;
dirx*=invLength;
diry*=长度;
//产生+/-3°的角度扰动
qreal=静态(qrand()%6-3)*M_PI/180.0;
qreal xperturbanation=cos(α扰动);
qreal-yperturation=sin(α扰动);
dirx=dirx*xperturbanation-diry*yperturbanation;
diry=diry*xperturbanation+dirx*yperturbanation;
GraphicsCircle*circle=新的GraphicsCircle(dirx,diry,-140195);
附加项(圆圈);
-140195是线条创建的基础。看起来我已经按照你说的做了,我相信。假设你的线条有一个特定的
角度,如果你想将子弹移动到该方向的某个距离,你必须:
// 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,-140195);
将圆放置到坐标(-140195),则应使用
GraphicsCircle * circle = new GraphicsCircle(dirx, diry, newX, newY);
addItem(circle);
…将其放置到新坐标。角度位于cannonarm->setRotation(360-line.angle())
在不同的函数中。偏移量只是将设置位置放置在不同的位置,而不是与设置的原点设置位置的确定距离。知道为什么吗?从您的代码中,似乎您的角度以度表示。我相应地编辑了我的答案。为您提供了代码,以便您可以准确地看到我所说的内容。我我试过了,但我得想点别的办法。偏移量离直线太远了。但它与函数mousemoveevent
和创建QLineF arm(cannonP1->pos(),e->scenePos()有关
好的,很抱歉,但我真的不明白你在看什么。想办法更好地解释你需要什么,我会再试一次。从你的代码中有很多我不明白的地方。我以为你说你想把子弹放在线的另一端,但从你的代码来看,你似乎只是在尝试不这样做o添加一个小的随机位移。你到底想实现什么?GraphicsCircle*circle=新的GraphicsCircle(dirx,diry,-140195);
在(-140195)场景坐标处添加一个圆。该位置是lineitemcannon=新的QgraphicsineItem(x1,y1,x1+50,y1);
。该线在顶点处旋转(-140195)以360度角移动。我试图弄清楚的是,将每个图形放置在行项目以该360度角移动的行的前面。该行与mousemoveevent关联,因此它可以指向鼠标在场景中的任何位置。再次编辑。再试一次。