- Home /
How can I make an object follow another's path with some time delay?
I need to make an object move exactly as another one, but with a delay of a few seconds. The "master" object's movements are not predictable. I have tried a lot of different approaches, such as using the Invoke and Sleep method, but nothing seems to have the desired effect. Help would be so much appreciated!
How is the master object moved? Can't you just save whatever variable is moving it and then apply it to the other object X seconds later?
The master object is moved by motion capture input using $$anonymous$$iddleVR. I have tried somehow saving the position variables in an array but I haven't found a way to make this approach work..
How about putting a script on the master object that sends its position to the following object when the master moves? The receiving object could then delay and execute every received position change?
Easier said than done. Since the master object is moving constantly, many not yet executed positions must be stored before being used my the slave object. I have tried writing them all in an array and having the slave object grab a position at the according time, but only got errors.
Have you tried just feeding it positions with a yield WaitForSeconds()
statement in front?
Answer by mattssonon · Oct 15, 2013 at 12:33 PM
Which error are you getting? Are you coding in JS, because yield WaitForSeconds()
is only valid in JS, in C# it would be yield return new WaitForSeconds(5);
.
Answer by Statement · Oct 15, 2013 at 12:38 PM
There are at least two parts to the problems. One is storing the data and revisiting it for the "ghost" object. Another is dealing with prediction since just copying the position it had one frame may not give the smoothest experience if the game is not running at a solid frame rate.
Basically, you would keep an array large enough to store time and transformation position (time, position, rotation, scale, whatever you need?). If your game runs at 30 fps and you need 2 second delay, you need 30*2=60 elements in the array. If your game runs at 60 fps and you need 2 second delay, you need 60*2=120 elements in the array. You can also approximate by only recording position every x frames.
Each frame, record the timestamp and the positional data. Use an indexer variable that you keep incrementing that loops around to the start of the array once it hits the end of it. Something like this:
data[i] = someData;
i = (i + 1) % data.Length;
When it comes to reading the data, keep another indexer or time variable and find the two entries in your array between "last update" and "now", and get a new position by interpolating the "then" and "now" for the ghost. You can think of this as a circular array with two indexers chasing each other.
If you've thought about the problem for a bit, you'll also realise that your game might potentially run at variable frame rates. Figuring out a stable system may take some thinking to get it right.