How to store the last 20 transform.position(vector3s) of an moving object in runtime and make a direction vector out of it?

Hey there!

An gameobject driven by a motion controller (PSmove/Move.Me) is doing some movements… I need the current direction of this gameobject. Not the direction of where it is facing, but the direction it is moving in space.

My attempt was to save the first and the next position of it.
Something like this:

		Quaternion movingDirection ;
		GameObject myController;
		Vector3 pos1;
		Vector3 pos2;
		
		pos1 = myController.transform.position;
		movingDirection = Quaternion.LookRotation (pos2 - pos1);
		pos2 = myController.transform.position;

But this isn’t working well because the space (0 frame) between them is to small to calculate a steady direction.

So I think it could be much more steady if I could store the last maybe 20 positions of the gameobject to calculate the direction out of it.

My problem is I don’t know how to store the last 20 transform.positions of a moving gameobject and a also don’t know how the calculate a direction(Quaternion) out of it.

Do someone has a solution?

For storing the last 20 transforms, check out the queue data structure, if you’re not familiar with it already.

Then, check out this pseudo code:

Queue<Transform> transformQueue = new Queue<Transform>();
int maxQueueSize = 20;

// elsewhere...
if(transformQueue.Count() >=  maxQueueSize )
{
  transformQueue.Dequeue();
}
transformQueue.Enqueue(this.transform);

For determining the direction, would an average be what you’re looking for? Try:

var average = Quaternion.Identity;
foreach(var xform in transformQueue)
{
  average += xform.rotation;
}
average /= transformQueue.Count();

Edit:
After looking at your problem a bit more, I think we’re trying to solve the wrong thing. The issue is that there isn’t enough time passing between when you get pos1 and pos2 – as you say, it’s 0 frames. I may be misreading what you’ve done here, but try the following:

Quaternion movingDirection;
GameObject myController;
Vector3 currentPos;
Vector3 previousPos;
 
currentPos = myController.transform.position;
movingDirection = Quaternion.LookRotation (currentPos - previousPos);
previousPos = currentPos;

This will:

  • grab the most recent position and store it in pos1
  • calculate the look rotation for the vector from the last position (pos2) to the new position (pos1)
  • Store the most recent position in pos2 for use as the ‘last position’ next frame.

I changed your subtraction around, since you want the new vector computation to be in the form of (to - from), instead of (from - to).
I changed the names of your variables because I kept getting confused.
I remain unconvinced that we are trying to solve the right thing.