| XNA Platformer Starter Kit - Save Player's Position (PC) |
| Written by Jeff Brown |
Save/Load players position
UPDATE: I wrote a tutorial for saving/loading on the Xbox 360 here.
using System.IO;
In Player.cs add the following after Vector2 position: Vector2 loadedPosition;
Now in the Player constructor, add the following if/else statement, overwritting the current Reset method: //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: //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(). 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); } } As always, drop me a line if something doesn't work or you'd like to suggest a tutorial or just need some help. This e-mail address is being protected from spambots. You need JavaScript enabled to view it |