Saving where your player left off on PC
Save/Load feature in Platform Starter Kit. (Saves the player's position, so you can start where you left off) (NOTE: works with PC only)
UPDATE: You can find a tutorial for saving/loading on the 360 here: XNA 3.1 | XNA 4.0
In this tutorial I'm going to create a hotkey (S) that saves the player's current position into a text file. You can then use this text file when loading a level to have your player start where you left off. You could even combine this with the checkpoint tutorial, so if you save and quit you'll load at the last checkpoint you hit. Splicing things together is an awesome way to learn (for me at least) so I'll leave that to you.
At the top of Player.cs we need to add the following using statements:
1 | using System.IO; |
In Player.cs add the following after Vector2 position:
1 | Vector2 loadedPosition; |
Now in the Player constructor, add the following if/else statement, overwritting the current Reset method:
1 2 3 4 5 6 7 8 9 10 11 | //What this does is check to see if //you have a save file, and load //it if you DO have one. Otherwise it //loads your player as it did before. if (File.Exists("playerPosition.txt")) { LoadPosition("playerPosition.txt"); Reset(loadedPosition); } else Reset(position); |
Now in the GetInput method we'll add a hotkey to save our game:
1 2 3 4 5 6 | //This should drop right in as long as you place it under //KeyboardState keyboardState... This shouldn't be the final //version of your save, because if you hold down the S button //the save function will be called a lot of times... if(keyboardState.IsKeyDown(Keys.S)) SavePosition("playerPosition.txt"); |
At the very bottom, I added the next couple methods, right after Draw().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | private void SavePosition(string path) { //using the default Platform Starter Kit, //the players position can be accessed using //'position'. So when using position below //in the save function, a Vector2 will be //saved with the current player's position using (StreamWriter writer = new StreamWriter(path)) { //We call this twice, and save the X variable //on the 1st line and the Y on the second. //This makes things really easy when //loading the values in LoadPosition(). writer.WriteLine(position.X); writer.WriteLine(position.Y); } } private void LoadPosition(string path) { using (StreamReader reader = new StreamReader(path)) { //Reads one line each time we call it, and since it's //only 2 lines the following should do fine for now. string line = reader.ReadLine(); loadedPosition.X = int.Parse(line); string line2 = reader.ReadLine(); loadedPosition.Y = int.Parse(line2); } } |