Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Awesomely Hacky user respawn location code.
/// <summary>
/// Restores the player to the starting point to try the level again.
/// </summary>
public void StartNewLife()
{
//First try at default start position
Player.Position= start;
//get the distance from the player the enemies need to be
var playerRange = Enumerable.Range((int)Player.Position.X - 3, (int)Player.Position.X + 3);
//if player bounding box is not intersecting with any enemy then respawn
var livingEnemies = enemies.Where(x => !x.IsDead );
//using the default back buffer so we can get a number that is guarnteed to be inside the screen
Vector2 playerXoffset = new Vector2(GraphicsDeviceManager.DefaultBackBufferWidth/8, 0f);
//Incrememt players x position while player is intersecting an enemy and is on the same y plane as the enemy
while (livingEnemies.Where(x => playerRange.Contains((int)x.Position.X) && x.Position.Y==Player.Position.Y).Count() > 0)
{
//move the player
Player.Position+=playerXoffset;
//Reset the player offset
playerRange = Enumerable.Range((int)Player.Position.X - 3, (int)Player.Position.X + 3);
//If Player is outside the bounds of the screen
if (Player.Position.X > GraphicsDeviceManager.DefaultBackBufferWidth)
{
//Try for the default spawn point
Player.Position = start;
}
}
//reset the state of the player(from dead to alive)
Player.Reset();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment