moving object to a point in a straight line

Started by
3 comments, last by haegarr 17 years, 5 months ago
as title says: I have easily managed to do this. | | | \ moving up and left and I am wanting to do something like. \ long double dx = moveToPosX - rcSprite.x; long double dy = moveToPosY - rcSprite.y; // float xDelta = cos (atan2(dx, dy)); //float yDelta = sin (atan2(dx, dy)); long double magnitude = sqrt ((dx*dx) + (dy*dy)); if( rcSprite.x !=moveToPosX){rcSprite.x += dx/magnitude;} if( rcSprite.y !=moveToPosY){rcSprite.y += dy/magnitude;} I tried something like what is above but the cos (atan2()) was getting an compiler error. I included math.h and cstdlib.h. does anyone have another way or better one of doing it.
Advertisement
math.h should be sufficient for sin and cos. It would be better to post the said compiler error to let us know more about what the compiler complains about.

However, trigonometrics are not needed for what you want to do. The not out-commented code in your snippet should in principle do the job. But you should be aware of:
(1) long double is presumbly oversized for your needs and slows down the app unneccessarily
(2) you may divide "magnitude" by a speed value
(3) comparing floating point values by != (or friends) is not good due to numerical problems (the actual type of rcSprite.x and moveToPosX isn't shown, but perhaps they are also floating point values)
When moving from point A (at time 0) to point B (at time 1), the position X at any given time t is:

X(t) = A + (B-A)*t

If you want to arrive at time T instead of time 1, the formula becomes:

X(t) = A + (B-A)*(t/T)

In particular, if you want a constant speed of v, then

T = |B-A| / v

So:

object.X = object.A + (object.B - object.A) * (t / object.T);

If you really insist on using euler integration, then you can use:

// Initializationobject.pos = A;object.dir = (B - A) / T;// Iterationobject.pos += object.dir * dt;

thanks that looks good, could you tell me what object.t is
object.X = object.A + (object.B - object.A) * (t / object.T);
x co-ordinate = x co-ordinate (MovingToThisX - x co-ordinate)*(time/?)
where time = |B-A| / speed


and dt
object.pos += object.dir * dt;
im guessing dt is change in time?
That object.X is the linear position interpolation starting at the original object.A position and ending at the object.B position. It is, as ThoorVyk has shown, passed in time T derived from a given speed. Notice that his suggestion doesn't use the _current_ positions but the _remembered_ (i.e. stored for t==0) positions to calculate T once.

Yes, dt is the time elapsed since the last recent position update. The object.dir would correctly be named object.vel (i.e. velocity).

This topic is closed to new replies.

Advertisement