Qt立即旋转动画

Qt instantly rotate animation

本文关键字:动画 旋转 Qt      更新时间:2023-10-16

我知道这可能是一个愚蠢的问题,但我似乎真的无法在任何地方找到答案。我创建了一个这样的三角形:

    QPolygonF triangle;
    triangle.append(QPointF(0., -15));
    triangle.append(QPointF(30., 0));
    triangle.append(QPointF(0., 15));
    triangle.append(QPointF(15., 0));

这个三角形将代表我地图上的一辆汽车,我需要为它制作动画。所以我做了以下工作:

    QGraphicsItemAnimation *animation;
    QGraphicsPolygonItem *clientCar;
    QTimeLine *timer;
    animation = new QGraphicsItemAnimation;
    timer = new QTimeLine(10000);
    timer->setFrameRange(0, 100);
    clientCar = scene->addPolygon(triangle, myPen, myBrush)
    animation->setItem(clientCar);
    animation->setTimeLine(10000);
    animation->setPosAt(0.f / 200.f, map.street1);
    animation->setRotationAt(10.f / 200.f, 90.f);
    animation->setPosAt(10.f / 200.f, map.street2);
    animation->setRotationAt(20.f / 200.f, 180.f);
    animation->setPosAt(20.f / 200.f, map.street3);
    scene->addItem(clientCar);
    ui->graphicsView->setScene(scene);
    timer->start();

问题是,当它到达十字路口(道路交叉口)时,它应该旋转,以便面对接下来要走的道路。正如你在上面看到的,我尝试使用 setRotationAt(),但它所做的是在交叉点之间缓慢旋转,直到到达下一个交叉点。它应该在瞬间转动,只有当它改变它的方式时。有什么帮助吗?

从文档中:

QGraphicsItemAnimation将在两者之间做一个简单的线性插值 最近的相邻计划更改以计算矩阵。为 实例,如果将项目的位置设置为值 0.0 和 1.0, 动画将显示项目在 这些职位。缩放和旋转也是如此。

线性插值部分就可以了。那你为什么不试试这个:

//animation->setPosAt(0.f / 200.f, map.street1);
//animation->setRotationAt(10.f / 200.f, 90.f);
//animation->setPosAt(10.f / 200.f, map.street2);
//animation->setRotationAt(20.f / 200.f, 180.f);
//animation->setPosAt(20.f / 200.f, map.street3);
static float const eps = 1.f / 200.f;
QVector<float> steps = {0.f, 10.f / 200.f, 20.f / 200.f};
QVector<QPointF> points = {map.street1, map.street2, map.street3};
QVector<float> angles = {0, 90.f, 180.f};
// initial conditions
animation->setPosAt(steps[0], points[0]);
animation->setRotationAt(steps[0], angles[0]);
// for each intersection
for(size_t inters = 1; inters < points.size(); ++inters)
{
    animation->setRotationAt(steps[inters] - eps, angles[inters - 1]);
    animation->setPosAt(steps[inters], points[inters]);
    animation->setRotationAt(steps[inters] + eps, angles[inters]);
}