- Home /
How to store previous locations in a list to teleport?
Basically: I have a character I want to be able to use an ability and they will 'snap' back to a position 5 seconds ago.
I understand the concept of how to do this: check the players location every second, store it in a list with 5 indexes (one for each second). If the player presses the button, set their transform position to the oldest index.
What I'm having trouble with is figuring out the code to actually get the list functioning in a way that it saves only the latest three values rather than appending infinite numbers onto the end.
Any help would be appreciated!
Answer by HappyMoo · Jan 01, 2014 at 05:57 AM
using System.Collections.Generic;
private int maxLength = 20; // Oh what the heck, let's save 4 times per second ;)
private Queue<Vector3> positions = new Queue<Vector3>(maxLength+1);
private Queue<Quaternion> rotations= new Queue<Quaternion>(maxLength+1);
void Store(Transform trans)
{
positions.Enqueue(trans.position);
rotations.Enqueue(trans.rotation);
if (positions.Count>maxLength)
{
positions.Dequeue();
rotations.Dequeue();
}
}
void Teleport(Transform trans)
{
trans.position = positions.Peek();
trans.rotation = rotations.Peek();
}
This is epic. Works really well on storing the information! I'm new to program$$anonymous$$g so I hadn't heard of Queue before!
Thanks for this. :)
No, that's exactly what you want, because Queue adds new items at the end.... so the first is always the oldest. Cheers!
edit: Oh wait, you already edited this... not fully awake yet :D
Haha, yeah I thought it was giving me the newest one but it was just a problem with the way I had it set up. I made some changes and it's working beautifully.
I wish I could upvote this but not enough karma yet! I'll be sure to bookmark it and come back and vote when I can. :)
Answer by trs9556 · Dec 31, 2013 at 03:05 AM
There is probably a more efficient way of doing it but because you already know it will be a max of 5 you can hard code a converter. So Make 2 arrays, a temp array and the actual array of locations.
When you add a new value to the "actual array" temporarily set all the current array values (except the one you are deleting) to the temp array. Delete the actual array then, and then make the temp array equal the actual array plus the current location.
Thanks that seems like a good approach. I was hoping there was a way to just say "insert" the new variable at index 0 and then 'shift' everything else down one place. ;P Guess it's not that easy! Thanks for the help. :)
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
How to draw text based on text above it? 0 Answers
get GameObject at 3 position in list 1 Answer
Can you set a string length when declaring it to a certain other number? 2 Answers
Array in Arrays (Item info type) 1 Answer