Make object orbit around another with Degrees only (Not radians only integer math) - math

I'm currently developing something that requires objects to orbit around another. Though, I am limited. I cannot use Radians to achieve this. I have access to sin and cos, and the degrees. But I cannot use radians (it breaks everything). Note that this is within Minecraft and the values there cannot hold floats or doubles. So, an answer like 0.017 will be 17. For this reason, I cannot use radians.
The function to calculate sin and cos is limited between -180 to 180. This means I cannot simply turn 0.787 radians into 787 radians, as that's out of the limit, and the answer returned would be completely wrong.
Right now the code would be something like this:
var distance = 100; // from the centre of orbit
var degrees = 45; // around a 360 degree orbit
var radians = degrees * (Math.PI / 180);
var x = Math.cos(radians) * distance;
var y = Math.sin(radians) * distance;
But that code completely relies on degrees being converted into radians. I cannot do this, because of Minecraft's integer limits, and how the functions calculate sin and cos. It just is simply not possible.
So the main questions is:
How can I find future position of an object with just the degrees, sin and cos?
(Perhaps base the answer as if the degrees were 45 for instance)
Here is a great example picture:

why not make your own LUT in fixed point ? something like this in C++:
const int fp=1000; // fixed point precision
const int mycos[360]={ 1000, 999, 999, 998, 997, 996, 994, 992, 990, ... }
float x,y,x0=0,y0=0,r=50,ang=45;
x = x0 + ( (r*mycos[ ang %360]) / fp );
y = y0 + ( (r*mycos[(ang+90)%360]) / fp );
Also you can write a script that will create the LUT for you. Each value in the LUT is computed like this:
LUT[i] = fp*cos(i*M_PI/180); // i = 0,1,2,...359
Now to normalize angle before use:
ang %= 360;
if (ang<0) ang+=360;
There are also ways to compute sin,cos tables with integer variables only out there. We used it in 8-bit era asm on Z80 for our stuff and later on x86 demos ... so it is possible to write code that would create it directly in minecraft script without the need of another compiler use.
You can even change the angular units to power of 2 instead of 360 so you can get rid of the modulo and also set the fp to mower of 2 -1 so you do not need even to divide. After some digging in my source archives I found my ancient TASM MS-DOS demo which uses this technique. After porting it to C++ and tweaking the constants here C++ result:
int mysinLUT[256];
void mysin_init100() // <-100,+100>
{
int bx,si=620,cx=0,dx; // si ~amplitude
for (bx=0;bx<256;bx++)
{
mysinLUT[bx]=(cx>>8);
cx+=si;
dx=41*cx;
if (dx<0) dx=-((-dx)>>16); else dx>>=16;
si-=dx;
}
}
void mysin_init127() // <-127,+127>
{
int bx,si=793,cx=0,dx; // si ~amplitude
for (bx=0;bx<256;bx++)
{
mysinLUT[bx]=(cx>>8)+1;
cx+=si;
dx=41*cx;
if (dx<0) dx=-((-dx)>>16); else dx>>=16;
si-=dx;
}
}
int mysin(int a){ return mysinLUT[(a )&255]; }
int mycos(int a){ return mysinLUT[(a+64)&255]; }
The constants are set so the sin[256] holds rough approximation of sinus within range <-100,+100> or <-127,+127> (depends on which init you call) and the angle period is 256 instead of 360. You need first call the mysin_init???(); once to init the LUT after that you can use mysin,mycos just do not forget to divide the final result by /100 or >>7.
When I render overlay of real and approximated circle using VCL:
void draw()
{
// select range
// #define range100
#define range127
// init sin LUT just once
static bool _init=true;
if (_init)
{
_init=false;
#ifdef range100
mysin_init100();
#endif
#ifdef range127
mysin_init127();
#endif
}
int a,x,y,x0,y0,r;
// clear screen
bmp->Canvas->Brush->Color=clWhite;
bmp->Canvas->FillRect(TRect(0,0,xs,ys));
// compute circle size from window resolution xs,ys
x0=xs>>1;
y0=ys>>1;
r=x0; if (r>y0) r=y0; r=(r*7)/10;
// render real circle
bmp->Canvas->Pen->Color=clRed;
bmp->Canvas->Ellipse(x0-r,y0-r,x0+r,y0+r);
// render approximated circle
bmp->Canvas->Pen->Color=clBlack;
for (a=0;a<=256;a++)
{
#ifdef range100
x=x0+((r*mycos(a))/100);
y=y0-((r*mysin(a))/100);
#endif
#ifdef range127
// if >> is signed (copying MSB)
x=x0+((r*mycos(a))>>7);
y=y0-((r*mysin(a))>>7);
// if >> is unsigned (inserting 0) and all circle points are non negative
// x=( (x0<<7)+(r*mycos(a)) )>>7;
// y=( (y0<<7)-(r*mysin(a)) )>>7;
// this should work no matter what
// x=r*mycos(a); if (x<0) x=-((-x)>>7); else x>>=7; x=x0+x;
// y=r*mysin(a); if (y<0) y=-((-y)>>7); else y>>=7; y=y0-y;
// this work no matter what but use signed division
// x=x0+((r*mycos(a))/127);
// y=y0-((r*mysin(a))/127);
#endif
if (!a) bmp->Canvas->MoveTo(x,y);
else bmp->Canvas->LineTo(x,y);
}
Form1->Canvas->Draw(0,0,bmp);
//bmp->SaveToFile("out.bmp");
}
the result looks like this:
Red is real circle and Black is circle using mysin,mycos. As you can see there are small deviations due to approximations accuracy but no floating point operation is used here. It is weird as the 3 methods of bitshift rsults in different numbers (it must be some optimization of mine compiler) the constants are tweaked for the first method.

Related

QWT moving canvas

I'm using QWT library for my widget, there are some curves on the canvas, like this:
void Plot::addCurve1( double x, double y, const char *CurveName,
const char *CurveColor,const char *CurveType )
{
...
*points1 << QPointF(x, y);
curve1->setSamples( *points1 );
curve1->attach( this );
...
}
So, all my curves have the same coordinate system. I'm trying to build navigation interface, so I could put step into TextEdit (for example) and moving by using this step, or I could go the end/start of my defined curve.
I've found method in QwtPlotPanner class, that gives me such opportunity:
double QWT_widget::move_XLeft()
{
//getting step from TextEdit
QString xValStr = _XNavDiscrepancies->toPlainText();
double xVal = xVal.toDouble();
// moveCanvas(int dx, int dy) - the method of QwtPlotPanner
plot->panner->moveCanvas(xVal,0);
x_storage = x_storage - xVal;
return x_storage;
}
So it works ok, but displacement in pixels and I need to stick it to my defined curve and it's coordinate system.
Qwt User's Guide tells, that:
Adjust the enabled axes according to dx/dy
Parameters
dx Pixel offset in x direction
dy Pixel offset in y direction
And this is the only information I've found. How can I convert pixels step into my coordinat system step? I need to go to the end of my curve, so I should return the last QPointF(x,y) of my curve and convert it to pixel-step? Or maybe I'm using wrong class/method?
Thank you very much :)
Thanks to #Pavel Gridin:
(https://ru.stackoverflow.com/a/876184/251026)
"For conversion from pixels to coordinates and back there are two
methods: QwtPlot::transform and QwtPlot::invTransform"

Calculate an intercept to an orbit for a given speed.

Background:
Attempting to write a game where 'FTL' travel is unaffected by gravity and acceleration is instant.
How do I calculate where a planet will be, given the Kepler orbit for the planet and a ships current position and its maximum FTL speed. (in m/s)
I can get the position of the planet for a given DateTime, but I'm struggling to figure out how to calculate where a planet will be, and where to send the ship to, without chasing the planet around the orbit.
I would iterate...
compute distance between planet and ship current position
from that you compute how much time your ship need to meet the target if the target would be static (not moving). Lets call this time t.
compute planet position in actual_time+t and compute t for this new position
remember last t lets call it t0. Then compute new t in the same way as in #1 but for position of the planet after t.
loop #2
stop if fabs(t-t0)<accuracy.
This iterative solution should be closer to the finding t with each iteration unless your planet moves too fast and/or ship is really too far or too slow (initial t is significant part or even bigger than the planets tropical year). In such case You usually first jump into the star system and then jump to planet (Like in original Elite).
For obscure planetary movements (like too small orbital period) you would need different methods but realize that such case implies either planet very near to star or very heavy system central mass like black hole...
In code with constant FTL speed it would look like this:
vec3 pp,ps=vec3(?,?,?); // planet and ship positions
double t,t0,time;
time=actual_time(); t=0.0;
for (int i=0;i<100;i++) // just avoiding infinite loop in case t/planet_orbit_period>=~0.5
{
t0=t;
pp = planet_position(time+t);
t=Length(pp-ps)/ship_FTL_speed;
if (fabs(t-t0)*ship_FTL_speed<=ship_safe_FTL_distance) break;
}
This should converge pretty quickly (like 5-10 iterations should be enough) Now t should hold the time needed for travel and pp should hold the position your ship should head to. How ever if i>=100 no solution was found so you first need to go closer to the system, or use faster FTL or use different method but that should not be the case for common in stellar system FTL as the travel time should be far less then the targets orbital period...
btw. this might interest you:
Is it possible to make realistic n-body solar system simulation in matter of size and mass?
[Edit1] slower than FTL translation drive
I give it a bit of taught and change the algo a bit. First it check all the positions along whole planet period with some step (100 points per period) and remember the closest time to travel to the ship regardless of periods of planet passed during the travel. Then simply "recursively" check around best location with smaller and smaller angle step. Here Preview of result:
And updated source (full VCL app code so just use/port what you need and ignore the rest)
//$$---- Form CPP ----
//---------------------------------------------------------------------------
#include <vcl.h>
#include <math.h>
#pragma hdrstop
#include "win_main.h"
#include "GLSL_math.h" // just for vec3
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TMain *Main;
//---------------------------------------------------------------------------
// constants
const double deg=M_PI/180.0;
const double t_day=60.0*60.0*24.0;
// view
double view_x0=0.0;
double view_y0=0.0;
double zoom=1.0;
// simulation
double sim_t=0.0,sim_dt=0.01*t_day;
//---------------------------------------------------------------------------
void toscr(double &x,double &y)
{
x*=zoom; x+=view_x0;
y*=zoom; y+=view_y0;
}
//---------------------------------------------------------------------------
class planet // Kepler body simplified to 2D axis aligned. For fully 3D orbit add mising orbital parameters and equations
{
public:
// input parameters
double a,b,t0,T; // major axis,minor axis, time where M=E=0.0 deg, orbital period
// computet parameters
double c1,c2,e;
void ld(double _a,double _b,double _t0,double _T)
{
// copy input orbital parameters
a=_a;
b=_b;
t0=_t0;
T=_T;
// prepare orbital constants
e=1.0-((b*b)/(a*a)); // eccentricity
if (e>=1.0) e=0; // wrong e
c1=sqrt((1.0+e)/(1.0-e)); // some helper constants computation
c2=a*(1-e*e);
//b=a*sqrt(1.0-e);
}
vec3 position(double t) // actual position relative to center mass of the system
{
int q;
vec3 p;
double E,V,r,M;
// compute mean orbital position M [rad] from time t
M=(t-t0)/T;
M-=floor(M);
M*=2.0*M_PI;
// compute real orbital position E [rad] from M
for (E=M,q=0;q<20;q++) E=M+e*sin(E);// Kepler's equation
// heliocentric ellipse
V=2.0*atan(c1*tan(E/2.0));
r=c2/(1.0+e*cos(V));
p.x=r*cos(V);
p.y=r*sin(V);
p.z=0.0;
return p;
}
void draw_orbit(TCanvas *scr)
{
int i;
double ang,x,y,r,V,E;
x=a; y=0; toscr(x,y);
for (i=2,E=0.0;i;E+=3.6*deg)
{
if (E>=2.0*M_PI) { E=0.0; i=0; }
V=2.0*atan(c1*tan(E/2.0));
r=c2/(1.0+e*cos(V));
x=r*cos(V);
y=r*sin(V);
toscr(x,y);
if (i==2){ scr->MoveTo(x,y); i=1; }
else scr->LineTo(x,y);
}
}
};
//---------------------------------------------------------------------------
class ship // Space ship with translation propulsion
{
public:
vec3 pos,dir; // position and translation direction
double spd,tim; // translation speed and time to translate or 0.0 if no translation
ship() { pos=vec3(0.0,0.0,0.0); dir=pos; spd=0.0; tim=0.0; }
void update(double dt) // simulate dt time step has passed
{
if (tim<=0.0) return;
if (dt>tim) { dt=tim; tim=0.0; }
else tim-=dt;
pos+=spd*dt*dir;
}
void intercept(planet &pl) // set course for planet pl intercept
{
if (spd<=0.0) { tim=0.0; return; }
const double d=1000000.0; // safe distance to target
/*
// [Iteration]
int i;
vec3 p;
double t0;
for (tim=0.0,i=0;i<100;i++)
{
t0=tim;
p=pl.position(sim_t+tim);
tim=length(p-pos)/spd;
if (fabs(tim-t0)*spd<=d) break;
}
dir=normalize(p-pos);
*/
// [search]
vec3 p;
int i;
double tt,t,dt,a0,a1,T;
// find orbital position with min error (coarse)
for (a1=-1.0,t=0.0,dt=0.01*pl.T;t<pl.T;t+=dt)
{
p=pl.position(sim_t+t); // try time t
tt=length(p-pos)/spd;
a0=tt-t; if (a0<0.0) continue; // ignore overshoots
a0/=pl.T; // remove full periods from the difference
a0-=floor(a0);
a0*=pl.T;
if ((a0<a1)||(a1<0.0)) { a1=a0; tim=tt; } // remember best option
}
// find orbital position with min error (fine)
for (i=0;i<3;i++) // recursive increase of accuracy
for (a1=-1.0,t=tim-dt,T=tim+dt,dt*=0.1;t<T;t+=dt)
{
p=pl.position(sim_t+t); // try time t
tt=length(p-pos)/spd;
a0=tt-t; if (a0<0.0) continue; // ignore overshoots
a0/=pl.T; // remove full periods from the difference
a0-=floor(a0);
a0*=pl.T;
if ((a0<a1)||(a1<0.0)) { a1=a0; tim=tt; } // remember best option
}
// direction
p=pl.position(sim_t+tim);
dir=normalize(p-pos);
}
};
//---------------------------------------------------------------------------
planet pl;
ship sh;
//---------------------------------------------------------------------------
void TMain::draw()
{
if (!_redraw) return;
double x,y,r=3;
vec3 p;
// clear buffer
bmp->Canvas->Brush->Color=clBlack;
bmp->Canvas->FillRect(TRect(0,0,xs,ys));
// Star
bmp->Canvas->Pen->Color=clYellow;
bmp->Canvas->Brush->Color=clYellow;
x=0; y=0; toscr(x,y);
bmp->Canvas->Ellipse(x-r,y-r,x+r,y+r);
// planet
bmp->Canvas->Pen->Color=clDkGray;
pl.draw_orbit(bmp->Canvas);
bmp->Canvas->Pen->Color=clAqua;
bmp->Canvas->Brush->Color=clAqua;
p=pl.position(sim_t);
x=p.x; y=p.y; toscr(x,y);
bmp->Canvas->Ellipse(x-r,y-r,x+r,y+r);
// ship
bmp->Canvas->Pen->Color=clRed;
bmp->Canvas->Brush->Color=clRed;
p=sh.pos;
x=p.x; y=p.y; toscr(x,y);
bmp->Canvas->Ellipse(x-r,y-r,x+r,y+r);
// render backbuffer
Main->Canvas->Draw(0,0,bmp);
_redraw=false;
}
//---------------------------------------------------------------------------
__fastcall TMain::TMain(TComponent* Owner) : TForm(Owner)
{
pl.ld(1000000000.0,350000000.0,0.0,50.0*t_day);
sh.pos=vec3(-3500000000.0,-800000000.0,0.0);
sh.spd=500.0; // [m/s]
sh.intercept(pl);
bmp=new Graphics::TBitmap;
bmp->HandleType=bmDIB;
bmp->PixelFormat=pf32bit;
pyx=NULL;
_redraw=true;
}
//---------------------------------------------------------------------------
void __fastcall TMain::FormDestroy(TObject *Sender)
{
if (pyx) delete[] pyx;
delete bmp;
}
//---------------------------------------------------------------------------
void __fastcall TMain::FormResize(TObject *Sender)
{
xs=ClientWidth; xs2=xs>>1;
ys=ClientHeight; ys2=ys>>1;
bmp->Width=xs;
bmp->Height=ys;
if (pyx) delete[] pyx;
pyx=new int*[ys];
for (int y=0;y<ys;y++) pyx[y]=(int*) bmp->ScanLine[y];
_redraw=true;
view_x0=xs-(xs>>3);
view_y0=ys2;
zoom=double(xs2)/(2.5*pl.a);
// draw(); Sleep(5000);
}
//---------------------------------------------------------------------------
void __fastcall TMain::FormPaint(TObject *Sender)
{
_redraw=true;
}
//---------------------------------------------------------------------------
void __fastcall TMain::tim_redrawTimer(TObject *Sender)
{
for (int i=0;i<10;i++)
{
sh.update(sim_dt);
sim_t+=sim_dt;
if (sh.tim<=0.0) sim_dt=0.0; // stop simulation when jump done
}
if (sim_dt>0.0) _redraw=true;
draw();
}
//---------------------------------------------------------------------------
The important stuff is in the two classes planet,ship then sim_t is actual simulated time and sim_dt is simulated time step. In this case simulation stops after ship reach its destination. The ship::tim is the time of travel left computed in the ship::intercept() along with direction for preset speed. The update should be called on each simulated time step ...

Perspective Projection effect correction

I was trying to plot 8 points in a 3D space from the 8 vertices of the above 3D sphare.
I used the following code:
#include "Coordinates2d.h"
#include "Point3d.h"
const double zoom = 500;
int main()
{
Coordinates2d::ShowWindow("3D Primitives!");
std::vector<Point3d> points;
points.push_back(Point3d(0,0,20));
points.push_back(Point3d(0,100,20));
points.push_back(Point3d(120,100,20));
points.push_back(Point3d(120,0,20));
points.push_back(Point3d(0,0,120));
points.push_back(Point3d(0,100,120));
points.push_back(Point3d(120,100,120));
points.push_back(Point3d(120,0,120));
for(int i=0 ; i<points.size() ; i++)
{
Coordinates2d::Draw(points[i], zoom);
}
Coordinates2d::Wait();
}
Where, the Point3D is like the following:
#ifndef _POINT_3D_
#define _POINT_3D_
#include "graphics.h"
#include "Matrix.h"
#include "Point2d.h"
#include <cmath>
#include <iostream>
struct Point3d
{
double x;
double y;
double z;
public:
Point3d();
Point3d(double x, double y, double z);
Point3d(Point3d const & point);
Point3d & operator=(Point3d const & point);
Point3d & operator+(int scalar);
bool operator==(Point3d const & point);
bool operator!=(Point3d const & point);
Point3d Round()
{
return Point3d(floor(this->x + 0.5), floor(this->y + 0.5), floor(this->z + 0.5));
}
void Show()
{
std::cout<<"("<<x<<", "<<y<<", "<<z<<")";
}
bool IsValid();
double Distance(Point3d & point);
void SetMatrix(const Matrix & mat);
Matrix GetMatrix() const;
Point2d ConvertTo2d(double zoom)
{
return Point2d(x*zoom/(zoom-z), y*zoom/(zoom-z));
}
};
#endif
#ifndef _COORDINATES_2D_
#define _COORDINATES_2D_
#include "graphics.h"
#include "Point2d.h"
#include "Point3d.h"
#include "Line3d.h"
class Coordinates2d
{
private:
static Point2d origin;
public:
static void Wait();
static void ShowWindow(char str[]);
private:
static void Draw(Point2d & pt);
public:
static void Draw(Point3d & pt, double zoom)
{
Coordinates2d::Draw(pt.ConvertTo2d(zoom));
}
};
#endif
I was expecting the output to be the following:
But the output became like the following:
I am actually interested to move my viewing camera.
How can I achieve my desired result?
I see from the comments that you achieved your desired result with a clever formula. If you're interested in doing it the 'standard' graphics way, using matrices, I hope this post will help you.
I found an excellent page written explaining projection matrices for OpenGL, which also extends to the general mathematics of projection.
If you want to go in depth, here is the very well written article, explains it's steps in detail, and is just overall highly commendable.
The below image shows the first part of what you're trying to do.
So the image on the left is the 'viewing volume' that you want your camera to see. You can see that in this case, the Center of Projection (basically the focal point of the camera) is at the origin.
But wait, you say, I don't WANT the center of projection to be at the origin! I know, we'll cover that later.
What we're doing here is taking the strangely shaped volume on the left, and converting it to what we call 'normalized coordinate' on the right. So we're mapping out viewing volume onto the range of -1 to 1 in each direction. Basically, we mathmatically stretch the irregularly shaped viewing volume into this 2x2x2 cube centered at the origin.
This operation is accomplished through the following matrix, again, from the excellent article I linked above.
So note you have six variables.
t = top
b = bottom
l = left
r = right
n = near
f = far
Those six variables define you viewing volume. Far is not labeled on the above image, but it is the distance of the furthest plane from the origin in the image.
The above image shows the projection matrix that puts out viewing volume into normalized coordinates. Once coordinates are in this form, you can make it flat by simply ignoring the z coordinate, which is similar to some of the work you have done (nice work!).
So we're all set with that for viewing things from the origin. But let's say we don't want to view from the origin, and would prefer to view from, say somewhere behind and to the side.
Well we can do that! but instead of moving our viewing area (we have the math all nicely worked out right here), it is perhaps counter intuitively, easier to move all the points we are trying to view.
This can be done by multiplying all of the points by a translation matrix.
Here is the wikipedia page for translation, from which I took the following matrix.
Vx, Vy, and Vz are the amount we want to move things in the x, y, and z directions. Keep in mind, if we want to move the camera in the positive x direction, we need a negative Vx, and vice versa. This is because we are moving the points instead of the camera. Feel free to try it and see, if you want.
You may also have noticed that both of the matrices I showed are 4x4, and your coordinates are 3x1. This is because the matrices are meant to be used with homogeneous coordinates. These seem strange because they use 4 variables to represent a 3D point, but its just x, y, z, and w, where you make w =1 for your points. I believe this variable is used for depth buffers, among other things, but it is basically ubiquitously present in graphics' matrix math, so you'll want to get used to using it.
Now that you have these matrices, you can apply the translation one to your points, then apply the perspective one to those points you got out. Then simply ignore the z components, and there you are! You have a 2D image from -1 to 1 in the x and y directions.

Cocos2D/Math - clean angle conversion

Mornin' SO!
I'm just trying to hone my math-fu, and I have some questions regarding Cocos2D in particular. Since Cocos2D wants to 'simplify' things, all sprites have a rotation property, ranging from 0-360 (359?) CW. This forces you to do some rather (for me) mind-humping conversions when dealing with functions like atan.
So f.ex. this method:
- (void)rotateTowardsPoint:(CGPoint)point
{
// vector from me to the point
CGPoint v = ccpSub(self.position, point);
// ccpToAngle is just a cute wrapper for atan2f
// the macro is self explanatory and the - is to flip the direction I guess
float angle = -CC_RADIANS_TO_DEGREES(ccpToAngle(v));
// just to get it all in the range of 0-360
if(angle < 0.f)
angle += 360.0f;
// but since '0' means east in Cocos..
angle += 180.0f;
// get us in the range of 0-360 again
if(angle > 360.0f)
angle -= 360.0f;
self.rotation = angle;
}
works as intended. But to me it looks kind of brute forced. Is there a cleaner way to achieve the same effect?
It is enough to do
float angle = -CC_RADIANS_TO_DEGREES(ccpToAngle(v));
self.rotation = angle + 180.0f;
for equivalent transformations
// vector from me to the point
CGPoint v = ccpSub(self.position, point);
actually, that's vector from point to you.
// just to get it all in the range of 0-360
you don't need to do that.

Move an object along waypoints in 2D

I created this function to move a unit along way points that are saved in list_. Every Unit has its own list_. move() is initially called with the speed (distance/step) every step. Then depending on the distance to the next way point three possible actions are taken.
Can you suggest any improvements?
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);
}
}
I'll hate myself for suggesting a deprecated way of doing things, but there's no reference to the replacing method :(
QGraphicsItemAnimation
It has addStep and linear interpolation stuff as a convenience.
It seems Qt devs would like you to use QTimeLine itself as a replacement.
I'd use Qt Animation Framework, more precisely 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();
I haven't tested this solution, but you should get the general idea.

Resources