gpt4 book ai didi

c++ - Qt 如何将项目添加到具有偏移量的场景中?

转载 作者:行者123 更新时间:2023-11-28 06:56:34 26 4
gpt4 key购买 nike

我在一行的底部添加了一个 QGraphicsItem(bullet)。 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 是创建线条的基础。看来我已经按照您所说的去做了,我相信。

最佳答案

假设你的线有一个特定的 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);

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

关于c++ - Qt 如何将项目添加到具有偏移量的场景中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23097420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com