Now we'll make the bullets lethal.
- First let's create a title screen that we can start on and return to after death.
- Create a
TitleStage.cs
file:
using System.Collections.Generic;
namespace Games.TestGame
{
public class TitleStage : Stage
{
public new Main Game {
get {
return (Main) base.
Game; } }
public TitleStage(Main game) : base(game)
{
}
protected override void OnEnter()
{
Graphics.SetClearColor(Game.Swatches.ClearColor);
Image font = Graphics.GetImage("Resources", "font");
int TEXT_DEPTH = 0;
Text titleText = Add(
new Text(font, Game.Swatches.White), TEXT_DEPTH);
titleText.Value = "TEST GAME";
titleText.Position = Graphics.Size / 2 + new Vector2i(-titleText.Width / 2, 30);
Text instructionText = Add(
new Text(font, Game.Swatches.White), TEXT_DEPTH);
instructionText.Value = "press A to start";
instructionText.Position = Graphics.Size / 2 + new Vector2i(-instructionText.Width / 2, -30);
}
protected override void OnUpdate()
{
base.OnUpdate();
if(Controls.A.JustPressed)
Game.SetStage(new GameStage(Game));
}
protected override void OnRender()
{
base.OnRender();
}
}
}
- To use the Text class, we'll need a 16x16 (character, not pixel) bitmap font image. In this case it's the
font.png
file in the Resources folder.
In TitleStage's OnEnter
method, we're creating some Text objects and adding them to the stage.
In TitleStage's OnUpdate
method, we're checking to see if the A button (by default the Z key) has been pressed this frame. If so, we're creating a new instance of GameStage and switching to that stage.
- In
GameStage.cs
, we'll create a new member variable (a List that can hold Bullets):
List<Bullet> _bullets = new List<Bullet>();
- When we create a new bullet, we need to keep track of it by adding it to this list.
- When we want to destroy a bullet, we have to remember to remove it from this list.
void AddBullet(Vector2f pos, bool movingDownward)
{
Bullet bullet = Add(new Bullet(movingDownward), 1);
bullet.Position = pos;
_bullets.Add(bullet);
}
public void RemoveBullet(Bullet bullet)
{
_bullets.Remove(bullet);
Remove(bullet);
}
- The bullet class now needs to call
((GameStage)Stage).RemoveBullet(this)
instead of just Stage.Remove(this)
.
- Let's also keep track of the player by adding a
_player
member variable to GameStage.cs
.
- Now that we have a reference to everything we need to access, we can check collision between the player and the bullets.
- In GameStage's
OnUpdate
method, check the distance (or distance squared, because it's faster) from each bullet to the player. If the distance is too low, then they're touching, and the player's dead.
protected override void OnUpdate()
{
base.OnUpdate();
foreach(Bullet bullet in _bullets)
{
float distSqr = (bullet.Position - _player.Position).LengthSquared;
if(distSqr < 150.0f)
{
Game.SetStage(new TitleStage(Game));
}
}
}
Prev Page :: Back to Index :: Next Page