Hi, i have a physics game, and in order for the loseGame condition to work, I need to detect if a game object has moved less than a specified distance over a specified time. can anybody point me in the right direction?
cheers.
ie: check how far the object has travelled in the last ‘x’ seconds, if it is less than ‘y’ units, do something.
I cant think of a straight forward way of doing this.
First you will want to work out the distance since the last update. So something like:
var distance: float=0;
function Update()
{
distance += Vector3.Distance(object.position, previousPosition);
previousPosition=object.Position;
}
Now what not clear to me is whether you wanting the player to have moved a total amount of time since he started or he has moved a at least x amount distance in the last y seconds.
If its the former then the above gives you everything you want. If its the later then you going to need something more elaberate.
You will need to sample a distance in time and work out what the distance is for the last number of samples.
So maybe something like:
var object: GameObject;
var NumberOfSamples: int=10;
var distances: float[];
var lastSampleSlot: int=0;
var previousPosition: Vector3;
function Start()
{
distances=new float[NumberOfSamples];
}
function Update()
{
var currentSampleSlot: int = Time.time % NumberOfSamples;
if( currentSampleSlot != lastSampleSlot)
{
distances[ currentSampleSlot] =0;
}
distances[ currentSampleSlot ] += Vector3.Distance(object.transform.position, previousPosition);
previousPosition=object.transform.position;
// sum all the values in the distances array to work out the distance in the last x samples secs.
var TotalSampleDistance: float =0;
for (var value: float in distances)
{
TotalSampleDistance += value;
}
}
For any given second, it works how far you have travelled in that second. It records that in the array. Everytime you move into a new slot, you clear out whatever was in there before.