Advertisement
  1. Game Development
  2. Programming

Make a Neon Vector Shooter in XNA: Basic Gameplay

Scroll to top
Read Time: 13 min
This post is part of a series called Cross-Platform Vector Shooter: XNA.
Make a Neon Vector Shooter in XNA: More Gameplay

In this series of tutorials, I'll show you how to make a neon twin stick shooter like Geometry Wars, which we will call Shape Blaster, in XNA. The goal of these tutorials is not to leave you with an exact replica of Geometry Wars, but rather to go over the necessary elements that will allow you to create your own high-quality variant.

I encourage you to expand upon and experiment with the code given in these tutorials. We'll cover these topics across the series:

  1. Set up the basic gameplay, creating the player's ship and handling input, sound and music.
  2. Finish implementing the gameplay mechanics by adding enemies, handling collision detection, and tracking the player's score and lives.
  3. Add a bloom filter, which is the effect that will give the graphics a neon glow.
  4. Add crazy, over-the-top particle effects.
  5. Add the warping background grid.

Here's what we'll have by the end of the series:

And here's what we'll have by the end of this first part:

The music and sound effects you can hear in these videos were created by RetroModular, and you can read about how he did so over at Audiotuts+.

The sprites are by Jacob Zinman-Jeanes, our resident Tuts+ designer. All the artwork can be found in the source file download zip.

Shape_Blaster_SpritesShape_Blaster_SpritesShape_Blaster_Sprites
The font is Nova Square, by Wojciech Kalinowski.

Let's get started.


Overview

In this tutorial we will create a twin-stick shooter; the player will control the ship with the keyboard, the keyboard and mouse, or the two thumbsticks of a gamepad. 

We use a number of classes to accomplish this:

  • Entity: The base class for enemies, bullets, and the player's ship. Entities can move and be drawn.
  • Bullet and PlayerShip.
  • EntityManager: Keeps track of all entities in the game and performs collision detection.
  • Input: Helps manage input from keyboard, mouse, and gamepad.
  • Art: Loads and holds references to the textures needed for the game.
  • Sound: Loads and holds references to the sounds and music.
  • MathUtil and Extensions: Contains some helpful static methods and extension methods.
  • GameRoot: Controls the main loop of the game. This is the Game1 class XNA automatically generates, renamed.

The code in this tutorial aims to be simple and easy to understand. It will not have every feature or a complicated architecture designed to support every possible need. Rather, it will do only what it needs to do. Keeping it simple will make it easier for you to understand the concepts, and then modify and expand them into your own unique game.


Entities and the Player's Ship

Create a new XNA project. Rename the Game1 class to something more suitable. I called it GameRoot.

Now let's start by creating a base class for our game entities.

1
2
abstract class Entity
3
{
4
	protected Texture2D image;
5
	// The tint of the image. This will also allow us to change the transparency.

6
	protected Color color = Color.White;
7
8
	public Vector2 Position, Velocity;
9
	public float Orientation;
10
	public float Radius = 20;	// used for circular collision detection

11
	public bool IsExpired;		// true if the entity was destroyed and should be deleted.

12
13
	public Vector2 Size
14
	{
15
		get
16
		{
17
			return image == null ? Vector2.Zero : new Vector2(image.Width, image.Height);
18
		}
19
	}
20
21
	public abstract void Update();
22
23
	public virtual void Draw(SpriteBatch spriteBatch)
24
	{
25
		spriteBatch.Draw(image, Position, null, color, Orientation, Size / 2f, 1f, 0, 0);
26
	}
27
}

All our entities (enemies, bullets and the player's ship) have some basic properties such as an image and a position. IsExpired will be used to indicate that the entity has been destroyed and should be removed from any lists holding a reference to it.

Next we create an EntityManager to track our entities and to update and draw them.

1
2
static class EntityManager
3
{
4
	static List<Entity> entities = new List<Entity>();
5
6
	static bool isUpdating;
7
	static List<Entity> addedEntities = new List<Entity>();
8
9
	public static int Count { get { return entities.Count; } }
10
11
	public static void Add(Entity entity)
12
	{
13
		if (!isUpdating)
14
			entities.Add(entity);
15
		else
16
			addedEntities.Add(entity);
17
	}
18
19
	public static void Update()
20
	{
21
		isUpdating = true;
22
23
		foreach (var entity in entities)
24
			entity.Update();
25
26
		isUpdating = false;
27
28
		foreach (var entity in addedEntities)
29
			entities.Add(entity);
30
31
		addedEntities.Clear();
32
33
		// remove any expired entities.

34
		entities = entities.Where(x => !x.IsExpired).ToList();
35
	}
36
37
	public static void Draw(SpriteBatch spriteBatch)
38
	{
39
		foreach (var entity in entities)
40
			entity.Draw(spriteBatch);
41
	}
42
}

Remember, if you modify a list while iterating over it, you will get an exception. The above code takes care of this by queuing up any entities added during updating in a separate list, and adding them after it finishes updating the existing entities.

Making Them Visible

We will need to load some textures if we want to draw anything. We'll make a static class to hold references to all our textures.

1
2
static class Art
3
{
4
	public static Texture2D Player { get; private set; }
5
	public static Texture2D Seeker { get; private set; }
6
	public static Texture2D Wanderer { get; private set; }
7
	public static Texture2D Bullet { get; private set; }
8
	public static Texture2D Pointer { get; private set; }
9
10
11
	public static void Load(ContentManager content)
12
	{
13
		Player = content.Load<Texture2D>("Player");
14
		Seeker = content.Load<Texture2D>("Seeker");
15
		Wanderer = content.Load<Texture2D>("Wanderer");
16
		Bullet = content.Load<Texture2D>("Bullet");
17
		Pointer = content.Load<Texture2D>("Pointer");
18
	}
19
}

Load the art by calling Art.Load(Content) in GameRoot.LoadContent(). Also, a number of classes will need to know the screen dimensions, so add the following properties to GameRoot:

1
2
public static GameRoot Instance { get; private set; }
3
public static Viewport Viewport { get { return Instance.GraphicsDevice.Viewport; } }
4
public static Vector2 ScreenSize { get { return new Vector2(Viewport.Width, Viewport.Height); } }

And in the GameRoot constructor, add:

1
2
Instance = this;

Now we'll start writing the PlayerShip class.

1
2
class PlayerShip : Entity
3
{
4
	private static PlayerShip instance;
5
	public static PlayerShip Instance 
6
	{
7
		get
8
		{
9
			if (instance == null)
10
				instance = new PlayerShip();
11
12
			return instance;
13
		}
14
	}
15
16
	private PlayerShip()
17
	{
18
		image = Art.Player;
19
		Position = GameRoot.ScreenSize / 2;
20
		Radius = 10;
21
	}
22
23
	public override void Update()
24
	{
25
		// ship logic goes here

26
	}
27
}

We made PlayerShip a singleton, set its image, and placed it in the center of the screen.

Finally, let's add the player ship to the EntityManager and update and draw it. Add the following code in GameRoot:

1
2
// in Initialize(), after the call to base.Initialize()

3
EntityManager.Add(PlayerShip.Instance);
4
5
// in Update()

6
EntityManager.Update();
7
8
// in Draw()

9
GraphicsDevice.Clear(Color.Black);
10
11
spriteBatch.Begin(SpriteSortMode.Texture, BlendState.Additive);
12
EntityManager.Draw(spriteBatch);
13
spriteBatch.End();

We draw the sprites with additive blending, which is part of what will give them their neon look. If you run the game at this point you should see your ship in the center of the screen. However, it doesn't yet respond to input. Let's fix that.


Input

For movement, the player can use WASD on the keyboard, or the left thumbstick on a gamepad. For aiming, they can use the arrow keys, the right thumbstick, or the mouse. We won't require the player to hold the mouse button to shoot because it's uncomfortable to continuously hold the button. This leaves us with a little problem: how do we know whether the player is aiming with the mouse, keyboard, or gamepad?

We'll use the following system: we'll add keyboard and gamepad input together. If the player moves the mouse, we switch to mouse aiming. If the player presses the arrow keys or uses the right thumbstick, we turn off mouse aiming.

One thing to note: pushing a thumbstick forward will return a positive y value. In screen coordinates, y values increase going downwards. We want to invert the y axis on the controller so that pushing the thumbstick up will aim or move us towards the top of the screen.

We'll make a static class to keep track of the various input devices and take care of switching between the different types of aiming.

1
2
static class Input
3
{
4
	private static KeyboardState keyboardState, lastKeyboardState;
5
	private static MouseState mouseState, lastMouseState;
6
	private static GamePadState gamepadState, lastGamepadState;
7
8
	private static bool isAimingWithMouse = false;
9
10
	public static Vector2 MousePosition { get { return new Vector2(mouseState.X, mouseState.Y); } }
11
12
	public static void Update()
13
	{
14
		lastKeyboardState = keyboardState;
15
		lastMouseState = mouseState;
16
		lastGamepadState = gamepadState;
17
18
		keyboardState = Keyboard.GetState();
19
		mouseState = Mouse.GetState();
20
		gamepadState = GamePad.GetState(PlayerIndex.One);
21
22
		// If the player pressed one of the arrow keys or is using a gamepad to aim, we want to disable mouse aiming. Otherwise,

23
		// if the player moves the mouse, enable mouse aiming.

24
		if (new[] { Keys.Left, Keys.Right, Keys.Up, Keys.Down }.Any(x => keyboardState.IsKeyDown(x)) || gamepadState.ThumbSticks.Right != Vector2.Zero)
25
			isAimingWithMouse = false;
26
		else if (MousePosition != new Vector2(lastMouseState.X, lastMouseState.Y))
27
			isAimingWithMouse = true;
28
	}
29
30
	// Checks if a key was just pressed down

31
	public static bool WasKeyPressed(Keys key)
32
	{
33
		return lastKeyboardState.IsKeyUp(key) && keyboardState.IsKeyDown(key);
34
	}
35
36
	public static bool WasButtonPressed(Buttons button)
37
	{
38
		return lastGamepadState.IsButtonUp(button) && gamepadState.IsButtonDown(button);
39
	}
40
41
	public static Vector2 GetMovementDirection()
42
	{
43
			
44
		Vector2 direction = gamepadState.ThumbSticks.Left;
45
		direction.Y *= -1;	// invert the y-axis

46
47
		if (keyboardState.IsKeyDown(Keys.A))
48
			direction.X -= 1;
49
		if (keyboardState.IsKeyDown(Keys.D))
50
			direction.X += 1;
51
		if (keyboardState.IsKeyDown(Keys.W))
52
			direction.Y -= 1;
53
		if (keyboardState.IsKeyDown(Keys.S))
54
			direction.Y += 1;
55
56
		// Clamp the length of the vector to a maximum of 1.

57
		if (direction.LengthSquared() > 1)
58
			direction.Normalize();
59
60
		return direction;
61
	}
62
63
	public static Vector2 GetAimDirection()
64
	{
65
		if (isAimingWithMouse)
66
			return GetMouseAimDirection();
67
68
		Vector2 direction = gamepadState.ThumbSticks.Right;
69
		direction.Y *= -1;
70
71
		if (keyboardState.IsKeyDown(Keys.Left))
72
			direction.X -= 1;
73
		if (keyboardState.IsKeyDown(Keys.Right))
74
			direction.X += 1;
75
		if (keyboardState.IsKeyDown(Keys.Up))
76
			direction.Y -= 1;
77
		if (keyboardState.IsKeyDown(Keys.Down))
78
			direction.Y += 1;
79
80
		// If there's no aim input, return zero. Otherwise normalize the direction to have a length of 1.

81
		if (direction == Vector2.Zero)
82
			return Vector2.Zero;
83
		else
84
			return Vector2.Normalize(direction);
85
	}
86
87
	private static Vector2 GetMouseAimDirection()
88
	{
89
		Vector2 direction = MousePosition - PlayerShip.Instance.Position;
90
91
		if (direction == Vector2.Zero)
92
			return Vector2.Zero;
93
		else
94
			return Vector2.Normalize(direction);
95
	}
96
97
	public static bool WasBombButtonPressed()
98
	{
99
		return WasButtonPressed(Buttons.LeftTrigger) || WasButtonPressed(Buttons.RightTrigger) || WasKeyPressed(Keys.Space);
100
	}
101
}

Call Input.Update() at the beginning of GameRoot.Update() for the input class to work.

Tip: You may notice I included a method for bombs. We won't implement bombs now but that method is there for future use.

You may also notice in GetMovementDirection() I wrote direction.LengthSquared() > 1. Using LengthSquared() is a small performance optimization; computing the square of the length is a bit faster than computing the length itself because it avoids the relatively slow square root operation. You'll see code using the squares of lengths or distances throughout the program. In this particular case, the performance difference is negligible, but this optimization can make a difference when used in tight loops.

Moving

We are now ready to make the ship move. Add this code to the PlayerShip.Update() method:

1
2
const float speed = 8;
3
Velocity = speed * Input.GetMovementDirection();
4
Position += Velocity;
5
Position = Vector2.Clamp(Position, Size / 2, GameRoot.ScreenSize - Size / 2);
6
			
7
if (Velocity.LengthSquared() > 0)
8
	Orientation = Velocity.ToAngle();

This will make the ship move at a speed up to eight pixels per frame, clamp its position so it can't go off-screen, and rotate the ship to face the direction it's moving.

ToAngle() is a simple extension method defined in our Extensions class like so:

1
2
public static float ToAngle(this Vector2 vector)
3
{
4
	return (float)Math.Atan2(vector.Y, vector.X);
5
}

Shooting

If you run the game now, you should be able to fly the ship around. Now let's make it shoot.

First, we need a class for bullets.

1
2
class Bullet : Entity
3
{
4
	public Bullet(Vector2 position, Vector2 velocity)
5
	{
6
		image = Art.Bullet;
7
		Position = position;
8
		Velocity = velocity;
9
		Orientation = Velocity.ToAngle();
10
		Radius = 8;
11
	}
12
13
	public override void Update()
14
	{
15
		if (Velocity.LengthSquared() > 0)
16
			Orientation = Velocity.ToAngle();
17
18
		Position += Velocity;
19
20
		// delete bullets that go off-screen

21
		if (!GameRoot.Viewport.Bounds.Contains(Position.ToPoint()))
22
			IsExpired = true;
23
	}
24
}

We want a brief cooldown period between bullets, so add the following fields to the PlayerShip class.

1
2
const int cooldownFrames = 6;
3
int cooldownRemaining = 0;
4
static Random rand = new Random();

Also, add the following code to PlayerShip.Update().

1
2
var aim = Input.GetAimDirection();
3
if (aim.LengthSquared() > 0 && cooldownRemaining <= 0)
4
{
5
	cooldownRemaining = cooldownFrames;
6
	float aimAngle = aim.ToAngle();
7
	Quaternion aimQuat = Quaternion.CreateFromYawPitchRoll(0, 0, aimAngle);
8
9
	float randomSpread = rand.NextFloat(-0.04f, 0.04f) + rand.NextFloat(-0.04f, 0.04f);
10
	Vector2 vel = MathUtil.FromPolar(aimAngle + randomSpread, 11f);
11
12
	Vector2 offset = Vector2.Transform(new Vector2(25, -8), aimQuat);
13
	EntityManager.Add(new Bullet(Position + offset, vel));
14
15
	offset = Vector2.Transform(new Vector2(25, 8), aimQuat);
16
	EntityManager.Add(new Bullet(Position + offset, vel));
17
}
18
19
if (cooldownRemaining > 0)
20
	cooldownRemaining--;

This code creates two bullets that travel parallel to each other. It adds a small amount of randomness to the direction. This makes the shots spread out a little bit like a machine gun. We add two random numbers together because this makes their sum more likely to be centered (around zero) and less likely to send bullets far off. We use a quaternion to rotate the initial position of the bullets in the direction they're travelling.

We also used two new helper methods:

  • Random.NextFloat() returns a float between a minimum and maximum value.
  • MathUtil.FromPolar() creates a Vector2 from an angle and magnitude.
1
2
// in Extensions

3
public static float NextFloat(this Random rand, float minValue, float maxValue)
4
{
5
	return (float)rand.NextDouble() * (maxValue - minValue) + minValue;
6
}
7
8
// in MathUtil

9
public static Vector2 FromPolar(float angle, float magnitude)
10
{
11
	return magnitude * new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
12
}

Custom Cursor

There's one more thing we should do now that we have the Input class. Let's draw a custom mouse cursor to make it easier to see where the ship is aiming. In GameRoot.Draw, simply draw Art.Pointer at the mouse's position.

1
2
spriteBatch.Begin(SpriteSortMode.Texture, BlendState.Additive);
3
EntityManager.Draw(spriteBatch);
4
5
// draw the custom mouse cursor

6
spriteBatch.Draw(Art.Pointer, Input.MousePosition, Color.White);
7
spriteBatch.End();

Conclusion

If you test the game now, you'll be able to move the ship around with the WASD keys or or left thumbstick, and aim the continuous stream of bullets with the arrow keys, mouse, or right thumbstick.

In the next part, we will complete the gameplay by adding enemies and a score.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Game Development tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.