c++ Qt QGraphicsItemAnimation model of thrown ball

c++ Qt QGraphicsItemAnimation model of thrown ball

本文关键字:thrown ball of model Qt QGraphicsItemAnimation c++      更新时间:2023-10-16

>我对根据运动方程飞行的球的动画有问题

x = speed*cos(angle) * time;
y = speed*sin(angle) * time - (g*pow(time,2)) / 2;

我用QGraphicsEllipseItem 创建了一个QGraphicsScene

QGraphicsScenescene = new QGraphicsScene;
QGraphicsEllipseItemball = new QGraphicsEllipseItem(0,scene);

然后我尝试动画球

scene->setSceneRect( 0.0, 0.0, 640.0, 480.0 );
ball->setRect(15,450,2*RADIUS,2*RADIUS);

setScene(scene);
QTimeLine *timer = new QTimeLine(5000);
timer->setFrameRange(0, 100);
QGraphicsItemAnimation *animation = new QGraphicsItemAnimation;
animation->setItem(ball);
animation->setTimeLine(timer);

animation->setPosAt(0.1, QPointF(10, -10));
timer->start();

但是我不明白setPosat是如何工作的,以及在这种情况下如何使用我计算的x,y。

setPosAt 的官方 Qt 文档非常简短且难以理解。

您需要多次调用 setPosAt(),使用 0.0 到 1.0 之间的 (step) 的各种值。 然后,当您播放动画时,Qt 将使用线性插值在您设置的点之间平滑地制作动画,因为 Qt 将其"当前步长"值从 0.0 增加到 1.0。

例如,要使球沿直线移动,您可以执行以下操作:

animation->setPosAt(0.0, QPointF(0,0));
animation->setPosAt(1.0, QPointF(10,0));

。或者让球上升,然后下降,你可以做到:

animation->setPosAt(0.0, QPointF(0,0));
animation->setPosAt(0.5, QPointF(0,10));
animation->setPosAt(1.0, QPointF(0,0));

。因此,要获得您想要的弧线,您可以执行以下操作:

for (qreal step=0.0; step<1.0; step += 0.1)
{
   qreal time = step*10.0;  // or whatever the relationship should be between step and time
   animation->setPosAt(step, QPointF(speed*cos(angle) * time, speed*sin(angle) * time - (g*pow(time,2)) / 2);
}