Let's make some bullets for our player to dodge.
- Create a
bullet.png
image (also around 16x16 pixels) that's facing downwards, and put it in the Resources folder.
namespace Games.TestGame
{
public class Bullet : Entity
{
public new Main Game {
get {
return (Main) base.
Game; } }
float _moveSpeed;
public Bullet()
{
_moveSpeed = Mathf.Random(30.0f, 40.0f);
}
protected override void OnEnterStage(Stage stage)
{
base.OnEnterStage(stage);
}
protected override void OnLoadGraphics(Graphics graphics)
{
Image image = graphics.GetImage("Resources", "bullet");
_sprite = Add(
new Sprite(image, Game.Swatches.Bullet),
new Vector2i(-image.Width / 2, -image.Height / 2));
}
protected override void OnUpdate(double dt)
{
base.OnUpdate(dt);
Y -= _moveSpeed * (float)dt;
CheckBounds();
}
void CheckBounds()
{
Vector2f gameSize = (Vector2f)Stage.Game.Graphics.Size;
Vector2f mySize = (Vector2f)_sprite.Size;
if(Y < -mySize.Y * 0.5f)
{
Debug.Log("bullet removed: " + Position);
Stage.Remove(this);
}
}
}
}
The bullet automatically moves downwards, and removes itself from its containing stage when it goes below the bottom border of the screen. Since the stage is currently the only thing referencing the bullet, removing it will cause it to be destroyed.
- In
GameStage.cs
, create a new Coroutine to continuously spawn bullets just above the top of the screen:
IEnumerator SpawnBullets()
{
while(true)
{
yield return Delay(0.5f);
float PADDING = 10.0f;
Vector2f bulletPos = new Vector2f(Mathf.Random(PADDING, Graphics.Width - PADDING), Graphics.Height + PADDING);
Bullet bullet = Add(new Bullet(), 1);
bullet.Position = bulletPos;
}
}
- and start the coroutine in
OnEnter
:
protected override void OnEnter()
{
Graphics.SetClearColor(Game.Swatches.ClearColor);
StartCoroutine(SpawnBullets);
}
Now you should see a bunch of harmless bullets moving down the screen when you run the game.
Prev Page :: Back to Index :: Next Page