#### Archived

This topic is now archived and is closed to further replies.

# Average of two vectors

## Recommended Posts

I have this sprite, and it has a motion vector. I want it to randomly wander around, so every 500 ms or so it randomly creates a new vector. I want it to slowly move from the current vector to the new vector, so it looks smooth, not erratic. Right now I''m just finding the average of the X and Y components of the vectors and setting the motion vector to that, like this:

if (SDL_GetTicks() - TimeAtLastVectorChange > 200)
{

TimeAtLastVectorChange = SDL_GetTicks();

MovementVector.SetLength(200);	//200 pixels per second!

MovementVector.SetAngle(rand() % 360);

}

//Add the new vector and the old vector

int x = MovementVector.GetX();
int y = MovementVector.GetY();

int oldx = CurrentVector.GetX();
int oldy = CurrentVector.GetY();

CurrentVector.SetX((oldx + x) / 2);
CurrentVector.SetY((oldy + y) / 2);


It doesn''t seem to be working. The sprite still jerks around each time the vector changes. What''s wrong with it?

##### Share on other sites
LilBudyWizer    491
Try (1-t)*u+t*v while varying t from 0 to 1.

##### Share on other sites
What does that give me? X? Y? i don''t see right off how to use it.

##### Share on other sites
davepermen    1047
u is startpos (vector)
v is endpos (vector)
t is time (float)

(1-t)*u + t*v

for t = 0 results in (1-0)*u + 0*v = u => you''re at the startpos
for t = 1 results in (1-1)*u + 1*v = v => you''re at the endpos
for t = .5 results in .5u + .5v => you''re in the middle..

this function is often called lerp

vector lerp(vector start,vector end,float t) {
return (1-t)*start + t*end;
}

lerp is for Linear intERPolation.

"take a look around" - limp bizkit

##### Share on other sites
Those lerp functions look like they deal more with position than velocity - they''re just a way to find what the current position should be when you know the start position, the end position, and the time elapsed. Not real appropriate for your situation, as far as I can tell, Brad.

That is, assuming CurrentVector is the current movement vector and MovementVector is the new movement vector. Right? I think the previous posters assumed CurrentVector was position and MovementVector was movement. Before I go on, you should clarify this.

~CGameProgrammer( );

##### Share on other sites
CurrentVector is where the sprite is moving right now. MovementVector is the new direction the sprite should move in.

[edited by - BradDaBug on May 4, 2002 5:27:08 PM]

##### Share on other sites
Oluseyi    2115
quote:
Original post by CGameProgrammer
Those lerp functions look like they deal more with position than velocity

You can interpolate vector quantities, which makes them appropriate for the velocity as well.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ ]
[ MS RTFM [MSDN] | SGI STL Docs | Boost ]