Переместить объект вдоль путевых точек в 2D - PullRequest
1 голос
/ 06 декабря 2010

Я создал эту функцию, чтобы перемещать юнит вдоль путевых точек, сохраненных в list_. Каждый юнит имеет свой list_. move() изначально вызывается со скоростью (расстояние / шаг) каждого шага. Затем в зависимости от расстояния до следующей точки пути предпринимаются три возможных действия.

Можете ли вы предложить какие-либо улучшения?

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);
 }
}

Ответы [ 2 ]

1 голос
/ 06 декабря 2010

Я бы использовал Qt Animation Framework, точнее 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();

Я не тестировал это решение, но вы должны получить общее представление.

1 голос
/ 06 декабря 2010

Я возненавижу себя за то, что предлагаю устаревший способ ведения дел, но нет ссылки на метод замены: (

QGraphicsItemAnimation

Для удобства предусмотрены функции addStep и линейной интерполяции.

Кажется, разработчики Qt хотели бы, чтобы вы использовали QTimeLine в качестве замены.

...