2010-12-06 37 views
1

我创建了这个功能来沿着保存在list_中的路点移动一个单元。每个单位都有自己的list_。最初用每一步的速度(距离/步长)调用move()。然后根据距下一路点的距离采取三种可能的行动。沿着2D中的路标移动物体

你能提出任何改进建议吗?

void Unit::move(qreal maxDistance) 
{ 
// Construct a line that goes from current position to next waypoint 
QLineF line = QLineF(pos(), list_.firstElement().toPointF()); 

// Calculate the part of this line that can be "walked" during this step. 
qreal part = maxDistance/line.length(); 

// This step's distance is exactly the distance to next waypoint. 
if (part == 1) { 
    moveBy(line.dx(), line.dy()); 
    path_.removeFirst(); 
} 
// This step's distance is bigger than the distance to the next waypoint. 
// So we can continue from next waypoint in this step. 
else if (part > 1) 
{ 
    moveBy(line.dx() , line.dy()); 
    path_.removeFirst(); 
    if (!path_.isEmpty()) 
    { 
    move(maxDistance - line.length()); 
    } 
} 
// This step's distance is not enough to reach next waypoint. 
// Walk the appropriate part of the length. 
else /* part < 1 */ 
{ 
    moveBy(line.dx() * part, line.dy() * part); 
} 
} 
+1

如果您尝试为对象设置动画效果,则新的动画框架可能值得您阅读:http://doc.trolltech.com/latest/animation-overview.html – 2010-12-06 15:00:02

回答

1

我会恨自己建议的做事方式已过时,但有来替换方法:(无参考

QGraphicsItemAnimation

它addStep和线性插值的东西作为便利。

看来Qt的开发者希望您使用QTimeLine本身作为替换。

1

我会使用Qt动画框架,更确切地说QPropertyAnimation

// I use QPainterPath to calculate the % of whole route at each waypoint. 
QVector<qreal> lengths; 

QPainterPath path; 
path.moveTo(list_.first()); 
lengths.append(0); 

foreach (const QPointF &waypoint, list_.mid(1)) { 
    path.lineTo(waypoint); 
    lengths.append(path.length()); 
} 

// KeyValues is typedef for QVector< QPair<qreal, QVariant> > 
KeyValues animationKeyValues; 
for (int i(0); i != lenghts.count(); ++i) { 
    animationKeyValues.append(qMakePair(path.percentAtLength(lenghts.at(i)), list_.at(i))); 
} 

// I assume unit is a pointer to a QObject deriving Unit instance and that 
// Unit has QPointF "position" property 
QPropertyAnimation unitAnimation(unit, "position"); 
unitAnimation.setKeyValues(animationKeyValues); 
unitAnimation.setDuration(/* enter desired number here */); 
unitAnimation.start(); 

我没有测试此解决方案,但你应该得到的总体思路。

+0

我还需要处理单元的碰撞位置,每个步骤的损坏和其他事情,以及修改路径的时间。 QPropertyAnimation是否允许我访问它,或者只是在动画启动后执行动画。另外我的单位是QGraphicsItem的子类。我不确定QPropertyAnimation是否适用于QGraphicsScene。你怎么看? – problemofficer 2010-12-06 23:35:44