Arcade
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events Pages
Step 4: Bullets

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.
part4-1.png
  • Create a Bullet.cs file:
using System;
using GameAPI;
namespace Games.TestGame
{
public class Bullet : Entity
{
public new Main Game { get { return (Main) base.Game; } }
protected Sprite _sprite;
float _moveSpeed;
// constructor
public Bullet()
{
_moveSpeed = Mathf.Random(30.0f, 40.0f);
}
// called when this entity is added to a stage
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);
// change position
Y -= _moveSpeed * (float)dt;
// keep player within screen boundary
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); // tell our containing scene to get rid of us when we are fully out of bounds
}
}
}
}

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)
{
// wait
yield return Delay(0.5f);
// spawn bullet
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:
// called when this stage is entered
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.

part4-2.gif

Prev Page :: Back to Index :: Next Page