Category Archives: MonoGame

Jetboard Joust Devlog #68 – Ray Of Hope!

I felt the latest weapon deserved a post to itself as it took a bit longer than the others and I’m particularly pleased with the result.

It’s called the ‘Gamma Ray’ and I was deliberately going for a kind of retro 50s sci-fi vibe with it. As with the bulk of the weapons (probably more so), there’s actually very little to coding the mechanics of it – probably around 90% of the development time here was spent on the visuals.

The ‘ray’ effect is all created with a custom shader. At its heart it’s an approximated sine wave (calculated using the smoothstep algorithm) – to get it looking more ‘electric’ I vary the amplitude of the wave at random each cycle.

I had a lot of issues finding a technique for generating random numbers in HLSL that I was happy with. I tried out a couple of algorithmic solutions but none of these seemed to look much good to me. In the end I used a second texture as a ‘noise’ lookup table, I created this texture myself by rendering to a RenderTarget2D in MonoGame so I could be sure the ‘noise’ was perfectly distributed. I’ll probably write a simple tutorial post on this subject and include some PNGs with different type of randomness.

I didn’t like using a consistent wavelength for the shader as it seemed to make things too uniform so I tried varying the wavelength per frame. This looked much better but I ran into an issue where the ‘end’ of the ray looked weird if it didn’t taper out to a point, which it wouldn’t do when there wasn’t an exact number of wave cycles across the length of ray.

I tried fading out the end to get around this – this worked OK but not great and looked weird when the ray ‘collided’ with enemies or buildings. In the end I settled on a solution whereby I taper out both the amplitude and ‘stroke width’ of the wave to zero, this seems to work fine and, even with a fractional amount of cycles, the ray now always tapers out to a nice point!

Lastly I applied a raster effect to the wave (again in HLSL) and overlaid two different rays with wavelengths cycling at different rates. The wavelength of both waves in tweened using a ‘Bounce’ tween algorithm so it seems to cycle regularly but in a fairly non-linear fashion.

The concentric circles at the muzzle of the gun and at the point the ray hits something are created using the geometric shaders I discuss here, though I’ve added a raster effect and a gradual fade out.

Dev Time: 2 days
Total Dev Time: approx 134.5 days

previous | next

mockup_3x
One Of The First Drafts Of The Raygun Shader

mockup_3x
The Finished Raygun Effect

mockup_3x
The Gamma Ray In Action

mockup_3x
Gamma Ray vs Particle Storm
Advertisements

Jetboard Joust Devlog #63 – Geometric Pixel Shader Tutorial

Been spending the last couple of days working on some geometric pixel shaders that I can use for various in game lighting effects to further juice up my explosions etc.

These may well be of use to others so I thought I’d get them into a serviceable state and do a mini-tutorial on their usage. OK, maybe ‘tutorial’ is too grand a word but I’ve commented the code thoroughly at least! Links to the HLSL source files for these shaders are included at the bottom of this article (scroll down).

I’m assuming the reader has a basic knowledge of HLSL – if not then there’s an excellent introductory tutorial here.

The shaders provided both draw a user-defined number of concentric shapes. The stroke width and spacing between the shapes can be set via user-defined parameters, as can the amount the spacing and stroke width increases at each iteration.

A parameter ‘multiply_increments’ allows the user to set whether the spacing/stroke width increment as applied linearly (by addition) or exponentially (by multiplication).

The supplied texture is used to draw the shapes (I often use a 2×2 white square), a user-defined tint can be applied to this.

All sizes, widths etc are calculated as a proportion of the texture size so usually between 0.0f and 1.0f though you can go larger than 1.0f if you wish some of your outer shape to be drawn outside of the texture (and therefore cropped).

Setting the shader parameters from your .net code would look something like the code below. Adjust these parameters over time to get the kind of trippy effects you see in some of the example GIFs. Maybe you could smooth these parameter changes using LERPing?

mockup_3x
Two Geometric Shaders Overlaid
Microsoft.Xna.Framework.Graphics.Effect shader = Game.Content.Load (“circles”);

// The tint that will be applied to the texture – set all values
// to 1.0 to leave the texture untouched
Microsoft.Xna.Framework.Vector4 tint;
tint.W = 1.0f; // alpha – 0.0f – 1.0f
tint.X = 1.0f; // red – 0.0f – 1.0f
tint.Y = 1.0f; // green – 0.0f – 1.0f
tint.Z = 1.0f; // blue – 0.0f – 1.0f
shader.Parameters [“tint”].SetValue(tint);

// The size of the first shape to be drawn
shader.Parameters [“size”].SetValue ( 1.0f );

// The stroke width of the first shape to be drawn
shader.Parameters [“strokewidth”].SetValue ( 0.1f );

// The initial spacing between shapes
shader.Parameters [“spacing”].SetValue ( 0.1f );

// The number of shapes
shader.Parameters [“repeats”].SetValue ( 3 );

// The amount by which spacing increases for each consecutive shape drawn
shader.Parameters [“spacing_increment”].SetValue ( 0.0f );

// The amount by which stroke width increases for each consecutive shape drawn
shader.Parameters [“strokewidth_increment”].SetValue ( 0.0f );

// Whether the spacing/stroke width increment as applied linearly (by addition)
// or exponentially (by multiplication).
shader.Parameters [“multiply_increments”].SetValue ( false );

// Adjust depending on how you’re doing your rendering
SpriteBatch.Begin (…);
shader.CurrentTechnique.Passes[0].Apply ();
SpriteBatch.End (…);

Probably also worth mentioning are the settings required to get the ‘endless loop’ effect you see in these GIFs. It’s pretty straightforward if the spacing and stroke width of shapes is consistent, but if not you need to tween the strokewidth and spacing so that they are the same for the second shape at the end of the loop as they were for the first shape at the start of the loop. It took me a while to get my head round this.

The code below shows some example values – don’t try and cut/paste this as it uses my own tweening classes and a wrapper class for the shader itself. It should be good enough to get an idea of how to set things up though…

// Initial stroke width relative to texture size
float width = 0.0025f;

// My wrapper class for the shader
shader = GeometryShader.CircleShader ();

// Used by my wrapper class – the size I’m drawing the texture on screen
shader.ScaleX = 506;
shader.ScaleY = 506;

// Set up initial spacing and stroke width for the shader
shader.Spacing = width;
shader.StrokeWidth = width;

// Spacing and stroke width will increase by 50% for each concentric shape drawn
shader.SpacingIncrement = 1.5f;
shader.StrokeWidthIncrement = 1.5f;
shader.MultiplyIncrements = true;

// Sets up the values to tween the size of the outer shape over a 30 frame seamless loop
// First two values are the start and end size
shader.TweenSize = new Tween (1.0f, 1.0f + shader.Spacing/shader.SpacingIncrement + shader.StrokeWidth/shader.StrokeWidthIncrement, 30, Tween.Linear);

// Sets up the values to tween the spacing over a 30 frame seamless loop
// First two values are the start and end spacing
shader.TweenSpacing = new Tween (width, width / shader.SpacingIncrement, 30, Tween.Linear);

// Sets up the values to tween the stroke width over a 30 frame seamless loop
// First two values are the start and end stroke width
shader.TweenStrokeWidth = new Tween (width, width / shader.StrokeWidthIncrement, 30, Tween.Linear);

And here are the actual HLSL source files. Note that I am pretty much a beginner at this stuff myself so I make no guarantees as to the suitability of this code for any purpose and I would welcome any contributions towards making it execute more efficiently.

I have plans to add more shape types at a later stage and combine these into one uber-shader that also also shapes to be combined in different ways. Watch this blog for updates…

circles.fx | squares.fx

If this is of use to you I’d welcome more followers on Twitter.

Dev Time: 2 days
Total Dev Time: approx 123 days

previous|next

mockup_3x
Two Circle Shaders Slightly Offset

mockup_3x
Square Shader With Additional Rotation Applied

Jetboard Joust Devlog #54 – Smoke & Mirrors

For the past few days I’ve been working on adding some more ‘juice’ to Jetboard Joust – the sort of small details that don’t really add anything to gameplay per se but, when combined, add an awful lot to game feel (hopefully).

I’ll go over most of these in a separate post but one element seemed to deserve a post of it’s own – smoke.

I wanted to add smoke as a way of increasing a sense of ‘permanence’ to the combat. Explosions are over and done in less than a second but smoke could hang around for ten seconds or so and build up depending on how much destruction is going on.

I wasn’t after a ‘realistic’ smoke effect but something more stylised to fit in with the rest of the game art. It seemed logical to use circles as the base for the effect but I felt pretty sure I’d want these circles to increase in size over time, maybe quite dramatically, so I didn’t want to rely on scaling sprites for this. I decided to use custom shaders instead as this should give me much more control.

So the first step was to use a custom shader to draw a simple filled circle. Initially I thought the geometry behind this would be quite complex but, in fact, it’s just simple pythagoras. Here’s the approach in pseudo code…

// get coordinates relative to centre of circle
float x = 0.5-coords.x;
float y = 0.5-coords.y;

// fill the entire space
float radius = 0.5;

if ( x*x + y*y <= radius*radius )
{
// return a color
}
else
{
// discard
}

…I’d be lying if I said I got to this stage quickly though! Though it didn’t take me long to figure out the maths, I spent far too long passing the shader a region of a texture to draw rather than the entire texture and getting confused as to why my results were all off (forgetting that coords.x and coords.y are relative to the entire texture to be drawn, not the region). When I started passing a simple 2×2 image to the texture everything clicked into place.

Once I’d successfully drawn a filled circle it was pretty easy to expand that technique to draw concentric rings and the like, and to animate these by basing their radii on parameters that are passed to the shader and change each frame.

Next step was to find a way of applying motion to these circles that looked suitably smoke-like. I started by simple applying a uniform velocity to several circles distributed across a certain range, e.g. -60d to +60d, as well as increasing the circles size over time.

When I finally got this to work the way I intended it didn’t look too bad as a starting point so I added a couple more parameters to make things more interesting – a ‘deceleration’ parameter (so that the velocity of the circles decayed over time), and a ‘buoyancy’ parameter (so that the circles gradually floated upwards over time). I also decreased the opacity of the circles over time so that they gradually faded out.

This looked much better but the results were still far too uniform, forming very obvious geometric patterns as the circles intersected. To stop this I added a certain amount of randomisation to both the circles initial velocity and their ‘buoyancy’ – this produced a much more smoke-like effect – still stylised but not overly ‘geometric’.

I was almost there now but felt that the smoke cloud was dissipating too quickly and lacked some kind of ‘weight’ to it’s centre. I fixed this by adding additional batches of circles with a decreasing initial spread and velocity with the final one staying pretty much in the same place. This looked a lot better.

Lastly I experimented with adding pixelation to the shader so that the circles were drawn at the ‘game’ pixel resolution rather than the ‘screen’ pixel resolution. Unfortunately I felt this looked pretty crappy – one of those things that ‘should’ have worked but didn’t! So I left things as they were but I did add a gradually increasing amount of pixelation over time so that when the circles have pretty much faded out they kind of ‘dissolve’ out rather than just disappearing.

Actually I couldn’t stop there – I thought the centre of the smoke cloud looked too ‘solid’ to start with so added a small particle effect to imitate ash or something. It’s subtle but it just breaks things up a little.

I’m pretty happy with the final result – watch this space for a mini-tutorial on using shaders to draw geometric shapes. I think I might end up using that technique again in this game…

Dev Time: 1.5 days
Total Dev Time: approx 97.5 days

previous | next

mockup_3x
Successfully Drawing Circles With HLSL

mockup_3x
First Attempt At Multiple Circles – An Interesting Fail!

mockup_3x
Starting To Look More Smoke-Like But Still Too Geometric

mockup_3x
Adding Some Randomisation For A More Natural Effect

mockup_3x
The Final Shader With Pixel Dissolve

mockup_3x
The Final Smoke Effect In Game

Lerp Camera Motion Smoothing Tutorial and Example Code

Recently I’ve been revisiting at the way the camera works in Jetboard Joust – something that has been a continual thorn in my side throughout the project.

When researching how to make the camera movement better I came across many references to Lerp smoothing but I found few, if any, detailed explanations as to how this works in practice and (particularly) ways to get around its significant limitations. Cue this post, by the end of which we’ll have a class that’ll move an object smoothly towards a target point and ‘brake’ so it reaches it exactly no matter how often and by how much the target is changed.

I’m just concentrating on one axis of movement here for simplicity but this approach can easily be applied to 2D or 3D vectors. For those of you with short attention spans you can just download the final class here.

So… Lerp is a quasi-acronym for ‘linear interpolation’ and used to create smooth movement between two points. It’s often used to smooth out camera movement but can equally be applied to sprites or anything else in 2D or 3D space. The basic equation for Lerp is very simple, it takes a position and target, works out the difference between them and then returns a value a specified amount along that path. Only values >0 and <1 are generally meaningful.

public static float Lerp(float position, float target, float amount)
{
     float d = (value2 - value1) * amount;
     return value1 + d;
}

If you are using this equation to move an object and each frame call it with the object’s current position (keeping the other values the same) the object will move a smaller distance each frame which results in a ‘slowing down’ effect as the objects reaches its target. Here’s an example of this type of motion applied to a sprite. In this case the sprite is moving approx 480 pixels at a frame rate of 60fps with a Lerp value of 0.025.


Basic Lerp Smoothing

Now this looks pretty good already but, as you’ve probably figured out, there are issues. The first one is that using this approach the object will never actually reach its destination – this can result in a slightly jerky looking motion as it reaches the end of its trajectory as well as presenting potential issues if you want to do something when the destination is reached.

One way of resolving this is to implement a minimum amount of movement per frame. This can be anything you want but for many applications it makes sense for this to be one pixel.

Here’s a simple ‘Lerper’ class that implements this – each frame the amount of movement (LerpVelocity) is calculated and, if the absolute value of this is less the minimum velocity we clamp it at the minimum velocity. Of course this means that the object might now be in danger of moving beyond its target point so we check for this at well and make sure it doesn’t.

public static float Lerp(float position, float target, float amount)
public class Lerper
{
    public Lerper()
    {
        Amount = 0.025f;
    }

    // Returns the amount of movement at this stage of the lerp
    private float LerpVelocity(float position, float target)
    {
        return (target - position) * Amount;
    }

    public float Lerp(float position, float target)
    {
        float v = LerpVelocity(position, target);

	// If this is less than the minimum velocity then
        // clamp at minimum velocity
        if ( Math.Abs(v) 0) ? MinVelocity : 0 - MinVelocity;
        }

	position += v;
	// Now account for potential overshoot and clamp to target if necessary
        if ( (v= target))
        {
            position = target;
        }
        return position;
    }

    public float Amount
    {
        get;
        set;
    }

    public float MinVelocity
    {
	get;
	set;
    }
}

Here’s an example of this in action. As you can see it looks much better…


Lerp With Minimum Velocity Applied

Still we have limitations though if we’re looking for really smooth movement. The next glaringly obvious one is that Lerp is ‘ease out’ only, the object will be moving fastest at the start of the sequence which makes it look like it’s being fired from a slingshot rather than smoothly accelerating from rest.

To resolve this I’m going to apply an ‘Acceleration’ property to my Lerper class. This ensures that, if the object is increasing in speed, the increase doesn’t exceed a specified amount. This requires a variable to store the amount of movement each frame.

public class Lerper
{
    private float previous_velocity;

    public Lerper()
    {
        Amount = 0.025f;
        Acceleration = float.MaxValue;
    }

    // Returns the amount of movement at this staget of the lerp
    private float LerpVelocity(float position, float target)
    {
        return (target - position) * Amount;
    }

    // Returns the next position with lerp smoothing
    public float Lerp(float position, float target)
    {
        // get the amount to move
        float v = LerpVelocity(position, target);
        // don't allow increases in velocity beyond the specifed acceleration
        if ( v>0 && previous_velocity>=0 && v-previous_velocity>Acceleration )
        {
            v = previous_velocity + Acceleration;
        }
        else if (v < 0 && previous_velocity  Acceleration)
        {
            v = previous_velocity - Acceleration;
        }
        // If this is less than the minimum velocity then
        // clamp at minimum velocity
        if ( Math.Abs(v) 0) ? MinVelocity : 0 - MinVelocity;
        }
        // Remember the previous velocity
        previous_velocity = v;

        // Adjust the position based on the new velocity
        position += v;
        // Now account for potential overshoot
        if ( (v= target))
        {
            position = target;
        }
        return position;
    }

    public float Amount
    {
        get;
        set;
    }

    public float MinVelocity
    {
        get;
        set;
    }

    public float Acceleration
    {
        get;
        set;
    }
}

Here’s an example of this in action – now we have a nice ‘ease in’ to our Lerp motion. Here I’m using an acceleration value of 0.25f.


Lerp With Maximum Acceleration ‘Ease In’ Applied

There’s one other problem I’m going to address though. This ‘ease in’ effect works nicely if the object is initially at rest or moving in the same direction but if the object had previously been moving in the opposite direction we’re still going to get a nasty jolt. Here’s an example where I’m changing the destination to the opposite side before the previous Lerp has reached the end of its trajectory.


Sudden Changes In Direction Result in A Nasty Jolt

So we’re going to check for this in the code and again apply a maximum amount by which the velocity can change each frame. Remember that because we’re changing direction the absolute value of the current velocity at the point of change is the sum of the absolute value of both the current and previous velocities, ie a change in direction from 10 to -10 would result in a new velocity of -20.

A side-effect of this is that the object will probably end up moving away from the target until it’s gathered enough momentum to change direction. As the code that clamps to the target position assumes we are moving towards the target we have to max out the target value if this happens.

We also have a special case check for our minimum velocity here as we need to make sure that if the minimum velocity is applied its applied in the direction that moves towards the target (otherwise the object could get stuck moving in the wrong direction).

public class Lerper
{
    private float previous_velocity;

    public Lerper()
    {
        Amount = 0.025f;
        Acceleration = float.MaxValue;
        MinVelocity = 0;
    }

    // Returns the amount of movement at this staget of the lerp
    private float LerpVelocity(float position, float target)
    {
        return (target - position) * Amount;
    }

    // Returns the next position with lerp smoothing
    public float Lerp(float position, float target)
    {
        // get the amount to move
        float v = LerpVelocity(position, target);
        // don't allow increases in velocity beyond the specifed acceleration (ease in)
        if ( v>0 && previous_velocity>=0 && v-previous_velocity>Acceleration )
        {
            v = previous_velocity + Acceleration;
        }
        else if  (v  Acceleration )
        {
            v = previous_velocity - Acceleration;
            // we might actually end up moving away from the target
            // here in which case we adjust the target so we don't get
            // clamped to it later
            if (v  0 && previous_velocity  Acceleration )
        {
            v = previous_velocity + Acceleration;
            // we might actually end up moving away from the target
            // here in which case we adjust the target so we don't get
            // clamped to it later
            if (v > 0-MinVelocity)
                v = MinVelocity;
            else
                target = float.MinValue;
        }

        // If this is less than the minimum velocity then
        // clamp at minimum velocity
        if ( Math.Abs(v) 0) ? MinVelocity : 0 - MinVelocity;
        }
        // Remember the previous velocity
        previous_velocity = v;

        // Adjust the position based on the new velocity
        position += v;
        // Now account for potential overshoot and clamp to target if necessary
        if ( (v= target))
        {
            position = target;
        }
        return position;
    }

    public virtual void OnTarget(){}

    public float Amount
    {
        get;
        set;
    }

    public float MinVelocity
    {
        get;
        set;
    }

    public float Acceleration
    {
        get;
        set;
    }
}

Here’s what happens when you suddenly change the Lerp target with this code applied – as you can see we now have a nice smooth movement no matter how often we change the target value.


Lerp With Maximum Acceleration ‘Ease In’ Applied

And that’s pretty much it. You can download the final class file here – in the final version I’ve also added a MaxVelocity property, a delegate to be called when the object reaches its destination, and tidied up the code so its not quite so verbose.

If you are in the process of coding a camera for a 2D game I highly recommend you check out this excellent article.

If you are looking for something to move smoothly between two points over a specified number of frames then you’re probably better off using some kind of tweening rather than Lerp. Check out Robert Penner’s excellent tweening/easing functions or the ‘smoothstep’ algorithm approaches described here.

Hopefully this article is of use – if so please consider following me on Twitter.

Jetboard Joust Devlog #49 – Gun Control

This week I’ve added a couple of extra jetboarding enemies and a new weapon – and I think I have enough content now for a playable demo! Just need to to sort the main menu out (groan) add a few more sound fx and (probably) background music. Here’s a bit more about the new stuff that’s been added…

The Gatling Gun
In operation this is really like a rapid-fire pistol, therefore it was pretty easy to subclass the existing ‘pistol’ weapon and change a few parameters to get it working. The hardest thing was getting the recoil to feel right – I wanted enough recoil for it to feel slightly ‘out of control’ and unwieldy but (obviously) not enough to be unplayable. I’ve given it a slightly lower damage-per-bullet than the pistol but this is more than made up for by the rapid firing.

Improved Shotgun Blast
One thing I realised whilst playtesting was that the existing shotgun blast was just nuking everything within its range rather than taking account of the fact that some enemies would shield others from the blast. Fixing this accurately seemed like it would be a mathematical nightmare (I’m not too strong on geometry) but I managed to implement a slightly ‘fuzzy’ solution which I think will be good enough. What I do is order all the enemies that intersect the blast region by their distance from the gun barrel. I then iterate through them in order creating a vertical ‘blocked zone’ for each one based on the combined height of the previous enemies in the list. If more than 50% of the current enemy intersects this ‘blocked zone’ I assume it has been shielded from the blast.

The Assassin
This type of enemy is pretty similar to the omnipresent ‘minion’ only they don’t try and abduct babies, they just go all out for attacking the player. This enemy uses the ‘skullhead’ sprite that I’d already designed and required no additional AI work (just adjusting existing parameters) so it was really easy to get up and running, unlike the next one…

The Bodyguard
Bodyguards have a pretty specific AI in that their main aim in life is to protect other enemies that are in the process of baby-snatching. I thought this would be pretty simple to get working but it was a lot harder than I thought to get something that looked decent. This is the basic framework of rules I ended up with…

– Bodyguards seek out the closest baby-snatcher to protect
– Once a bodyguard gets close enough to protect someone they’ll never desert them
– Only two bodyguards can protect a baby-snatcher at one time
– If there’s more than one bodyguard protecting a baby-snatcher they’ll stand guard on opposite sides
– Bodyguards never stray to far horizontally from the baby-snatcher they;re protecting but they will move vertically to attack the player

…there’s a bit more to it than that but these are the key AI decisions that are made. Bodyguards have a lot of health but move relatively slowly and I’ve tried to design the sprite to reflect this, hence they look rather ‘chunky’ compared to the other jetboarding enemies.

I haven’t fully playtested all this yet but will be doing so over the next few days as I add the outstanding audio fx.

Dev Time: 3 days
Total Dev Time: approx 83 days

previous | next


Whoops – Too Much Recoil On The Gatling Gun

mockup_3x
The Final Gatling Gun In Action

mockup_3x
The Magic Shotgun – Enemies Should Shield Each Other!

mockup_3x
Fixing The Magic Shotgun

mockup_3x
Trying To get The Bodyguard Looking A Bit More ‘Hench’!

mockup_3x
Bodyguards Doing What They’re Paid To Do

mockup_3x
Assassin Enemies Wielding Gatling Guns – Beware!

Jetboard Joust Devlog #48 –Game (Not) Over

Since the last post I’ve mainly been tweaking – playing the game over and over again, adjusting the various difficulty parameters and noting down and fixing various bugs that crop up. My aim at this stage is to get to the point where I have an ‘alpha’ version that can exist as a playable demo, albeit with a very limited set of weaponry and enemies. I’m getting there!

So, in no particular order, heres some of the stuff I’ve been working on…

The Dawdle Police
I’ve made the ‘bastard‘ enemies operate similar to the ‘baiters’ in Defender in that they only appear once the player has spent a certain amount of time trying to complete a level and (unlike other enemies) don’t need to be destroyed in order to complete a level. More bastards appear the longer the player hangs around adding even more of a sense of urgency to the proceedings.

The Pyramid
Some of the more observant readers may be wondering why there are two warp gates that appear at the end of each level. Well, in a nod to ZX Spectrum ‘classic’ The Pyramid, the gate you choose affects the level you’ll appear in next, so rather than a linear arrangement of levels we have a pyramid-type structure with each row defining the difficulty level and each column a different combination of enemies, terrain and weaponry. I will probably add special collectables at certain locations to add an exploratory element to the game. I’ve always had this functionality planned from the start but have only just implemented it properly.

Mutant Frenzy
In another nod to Defender, now if you’re careless enough to let all your babies get abducted a ‘mutant frenzy’ is unleashed! Every jetboard-riding enemy mutates and every remaining attack wave is released. Basically it’s total chaos and you probably won’t last long after this happens!

Score Combos
Killing enemies in quick succession now ups a bonus multiplier which multiplies both the score and cash awarded. It’s a good way to earn extra cash and I like the way it adds to the ‘pinball’ feel of racking up large amounts of points.

Extra Lives
Extra life pickups now appear when a certain score threshold is reached. You’re going to need them!

Game Over
I’ve added a fixed number of lives per game and the ‘game over’ message. Spent quite a while tweaking the ‘game over’ effect!

Jetsuit and Jetboard Upgrades
I’ve now fully implemented the code that makes your jetboard and jetsuit upgradeable items. The upgrade state of all equipment is now persistent across games.

Plus a myriad of other small improvements and bugfixes.

I may now add one extra weapon type (machine gun) and possibly a couple of extra enemy types before moving on to add a few elements of missing game audio, background music, and then a first implementation of overall menu UI.

Dev Time: 5.5 days
Total Dev Time: approx 80 days

previous | next


Kill Enemies In Quick Succession For A Bonus Multiplier

mockup_3x
You’re Gonna Need An Extra Life Or Two…

mockup_3x
Must… Try… Harder… Next… Time…

mockup_3x
Your Jetsuit And Jetboard Are Now Fully Upgradeable

Jetboard Joust Devlog #47 –Having Difficulty With Difficulty

With all the core gameplay elements pretty much in place it’s time to get back to some serious gameplay testing and start thinking in more detail about how I manage the difficulty curve within the game.

I’d already put quite a bit of thought into this as discussed here, but, as is so often the case, Jetboard Joust has grown in complexity fairly significantly since I posted that and my ‘procedural difficulty’ code needed to be reworked in a major way.

I’m still starting from a similar standpoint in that I allocate a difficulty value for each level and then create random waves of enemies that total that difficulty score. Now, however, I have different RPG-style ‘character-levels’ of enemies and weaponry to consider.

Firstly what I do is allocate a series of character-level ‘stats’ to each enemy and weapon type. I set a minimum and maximum value for each stat and the values in between are calculated automatically. Some values (e.g. health, weapon range) are consistent across all enemies and weapons but not all. Every weapon and enemy has a ‘difficulty’ stat.

I then create an EnemyDefinition for each enemy/weapon combo. This is a lot of definitions as I have to have create a separate definition for every combination of each character-level of enemy and weapon.

When a level is created my first approach was to split the total difficulty score into a set of six ‘batches’ of enemies that are released at set time intervals. The enemies that make up each batch were chosen at random from the EnemyDefinition collection. If a batch of enemies is destroyed the next one is released immediately.

This worked pretty well but the combination of enemies was too random and in order to get a more playable selection I needed to implement a few restrictions…

1. Every enemy and weapon type have an ‘intro level’ so that they don’t appear until a certain level of the game has been reached.

2. Every enemy and weapon type have a’level up rate’ that affects the way their ‘character-level’ progresses throughout the game – so, for instance, an enemy with a ‘level-up rate’ of 2 and an ‘intro level’ of zero could only appear at character-level 1 for the first two levels of the game, then at character-level 1 or 2 for game levels 3 and 4 and so on.

3. Only certain enemies will try and abduct the alien babies(!) – as this is fundamental to the way the game plays I needed to ensure a certain amount of ‘baby-chasing’ enemies per batch. I know that sounds a bit dodgy!

After implementing these restrictions the enemy selection was much better but I realised the process was still flawed. As I was choosing enemies from the set of EnemyDefinitions at random (albeit with the above restrictions) the selection was skewed towards certain types of enemies. There would always be many more valid definitions for lower ‘intro-level’ enemies (especially as we have a definition for every character-level and weapon combo) resulting in far too many of certain enemy types in the game.

To solve this I needed to create a structure to store the valid EnemyDefinitions that was not simply a flat list – so I created the wonderfully-named EnemyDefinitionBucket class.

A EnemyDefinitionBucket contains a horrible-looking data structure that’s defined like this…

SortedDictionary<EnemyTypes, SortedDictionary<WeaponTypes, List>> dictionary;

..so first we have a collection of every valid EnemyType in the bucket, then for each EnemyType a collection of each valid WeaponType, and finally for each EnemyType/WeaponType combination a list of each valid character-level of enemy and weapon that fits that combination.

Now when I choose a random EnemyDefinition I first select a random EnemyType, then a random WeaponType, and finally a valid EnemyDefinition that matches that combination. This ensures that all enemies and weapons appear on equal footing.

Only that wasn’t quite good enough! In practice the enemy/weapon selection needs to be skewed towards those that have an ‘intro level’ nearest the current game level. Hence the reason I have used SortedDictionary rather than a standard Dictionary – this way the enemy and weapon type ‘keys’ can be indexed in order of ‘intro level’ and I can implement a sine-based distribution curve that favours the ‘higher’ items when choosing at random. The EnemyDefinitions are also stored in a sorted List and selected in a similar way.

Finally I think that’s done it, now on to tweaking the various ‘character stats’ which is another rabbit-hole.

And, sorry, this post doesn’t contain much to look at so I’ve just included some random gameplay footage – finally found an app Capto that grabs at 60fps!

Dev Time: 3 days
Total Dev Time: approx 74.5 days

previous|next

mockup_3x
The Current State Of Play

Jetboard Joust Devlog #46 –You Can’t Take It With You

Yeah, I know, been a bit quiet round here. Had a bit of time off!

Been working on some more ‘polish’, implementing stuff I’d been putting off for a while and getting various aspects of the gameplay to work together. Here’s what’s been on my ‘to do’ list these past few days…

Add More Cash
I only had one denomination of coinage which clearly wasn’t going to be enough to cover all the cash rewards in the game, not without spawning a ludicrous amount of pickups anyway, so I’ve designed and added a few more. Now there’s five different types of coin 1, 5, 10, 50 and 100. I may have to add a 500 later on.

Bloodstains
One of my favourite mechanics in the ‘Souls’ games is the way that, when you die, you lose all your ‘souls’ (the game’s currency) and can only retrieve them by returning to the place you last died and touching your bloodstain. It can be incredibly annoying losing all the ‘cash’ you’ve earned but it really makes dying something to be avoided (unlike in many modern games where dying is practically meaningless) and adds an extra tension to the next life too. I’ve implemented a similar mechanic whereby you lose all your cash on death and have to return to your abandoned jetsuit in order to retrieve it.

Weapon Unlocks
I’ve now properly implemented the feature whereby picking up an enemy’s jetboard unlocks the weapon they were carrying for your own use. A weapon crate will automatically spawn when this happens giving the user a chance to pick up the weapon they have just unlocked.

Upgrade Equipment
I’ve properly implemented this as part of the gameplay cycle so you are given a chance to upgrade equipment at the end of each level. This took longer than it should! Also added the jetsuit itself as an upgradeable item.

Redo Jetboard Particle FX
I was never that happy with the vertical thrust effect on the jetboard so I’ve redone this giving it a more ‘anti-gravity’ quality. I’ve also tweaked and re-aligned the particle fx for the horizontal thrust.

That’s it. I am getting there, slowly. The next task is to revisit the ‘difficulty’ algorithms for level creation to make them take account of different weapon and enemy levels.

Dev Time: 4.5 days
Total Dev Time: approx 71.5 days

previous


New Denominations Of Coinage

mockup_3x
The Infamous ‘Bloodstain’ Mechanic


Capturing An Enemy’s Weapon


Picking Up An Unlocked Weapon

Jetboard Joust Devlog #44 – Shotgun Logic

Time to leave enemies for the time being and move on to weaponry – really the last missing piece of the puzzle. If I’m going to make any new enemies they need to be tougher and it’s impossible to gameplay test them effectively with the underpowered pistol which is all I had implemented up to this point.

The first weapon I wanted to build was a shotgun, but before I got into designing the weapon itself I needed to think a little harder about how weapon swapping and ammo supply works in the game.

Up to this point if you run out of ammo you basically have no useable weapon available. This makes logical sense but seems kind of harsh. It becomes impossible to defend oneself so, unless there is an obvious ammo cache onscreen, death is pretty much inevitable. I needed to find a balance between keeping the necessity to drop down and pick up ammo caches (I like this part of the gameplay), not leaving the player totally ‘high and dry’ and not leaving them overpowered either.

My current solution to this is to use the pistol as a default weapon. If your current weapon runs out of ammo you will switch to the pistol automatically – if your pistol runs out of ammo then an ammo cache will automatically drop onscreen making it easy to reload but still, hopefully, enough of a pain to make the player try and avoid this situation if possible. Your ‘old’ weapon is placed in a weapon crate somewhere in the world meaning it can be retrieved and is not lost for good. These aspects of the game design may well need tweaking but at the moment this seems to provide a decent balance between the various parameters.

So, once the above was implemented, shotgun time! I thought the shotgun would be a pretty easy weapon to create but as it turned out I was wrong, no surprise there then.

First thing I did was work on the visuals. I ended up adding three different particle effects – one to represent the ‘pellets’, one for smoke from the barrel, and one as a kind of abstract explosion effect to give some idea of the effective range of the blast. I also added a very short sprite-based ‘muzzle flash’ animation. My weapon superclass already handles barrel recoil and recoil for the player so I put a nice bit of knockback in there to make the blast seem pretty weighty.

Lastly – collision detection. This is the part that I thought would be easy (as the shotgun blast is a one frame ‘hit check’) but turned out to be more complicated. You can’t get away with simple rectangle-based collisions (as I use in the rest of the game) as the blast range is really an arc, like a slice of pie. Fortunately some time ago I spent a while implementing some SAT-based collision detection routines in my game libraries so I could call on them now – luckily they worked (which is a good job as I remember SAT-based collision checking was pretty complex and I had no desire to go back rooting around that code)! What I do is approximate the blast ‘arc’ with a simple polygon and check whether that intersects the enemy’s collision rectangle. This seems to work fine (though I ended up widening the ‘hit range’ around the muzzle of the shotgun more than you see in the GIFs). I calculate the damage done to each enemy based on the distance from the muzzle both horizontally and vertically – a maximum 50% reduction in damage each way.

The next issue to raise it’s head was that I had to stop the shotgun blast being effective through buildings. This seemed like it was going to be complicated, I’d have to trace a line between the blast and the point it hit the enemy and see if any buildings intersected it, but I managed to implement a much cheaper solution which seems to work fine. All I do is see if there’s a side of a building between the shotgun muzzle and the enemy. If there is and the muzzle is below the level of the top of the building I assume the blast is blocked (as it would be the vast majority of the time). If the muzzle is above the top of the building and the top of the enemy is below the top of the building I also assume the blast is blocked. These two simple checks seem to cover off most scenarios realistically enough.

Once the shotgun was working as a weapon for the player I then needed to try arming the enemies! Because of the way I have structured my classes this was pretty simple but unfortunately it uncovered limitations in the enemy AI.

Up to this point I had been assuming an ideal place to shoot at the player is with the barrel of the weapon level with the centre of the player. This is still true with the shotgun but it won’t be true for all weapons (for example a grenade launcher) and there also needs to be additional logic for when an enemy decides whether to fire or not which takes into account the blast range of the shotgun.

So what I’ve done is implement two different methods as part of my Weapon superclass. One returns the ideal height at which to fire at the player and the other returns ‘true’ if the weapon is likely to hit the player if fired. These can both be overridden in the subclass to provide more weapon-specific logic. This architecture works great – enemies with shotguns are pretty deadly now and I’ll easily be able to extend to different weapon types to make enemies automatically change their behaviour based on which weapon they are carrying.

Last touch was to design some audio for the shotgun blast. I was going to leave any additional audio and do it all in one batch but seeing that shotgun fired and not make a sound was disturbing me!

Dev Time: 2.5 days
Total Dev Time: approx 62 days

previous | next

mockup_3x
Almost There With The Particle FX

mockup_3x
Working On Collision Detection

mockup_3x
Damn – Shotgun Blasts Shouldn’t Work Through Buildings

Jetboard Joust Devlog #43 – You Bastard!

The next enemy is the last from Defender I need to (loosely) implement. The Defender version is called the ‘baiter’, a small UFO that appears if you take too long to complete a level and gives you all kinds of grief. My version is similarly evil so I’m calling it simply ‘The Bastard’ – because it’s a bit of a bastard.

I thought I’d keep a ‘flying saucer’ aspect to the character design so we have a little alien dude piloting a UFO. It didn’t take me too long to get the basic design sorted but the animation was a bit of a pain. The little spinning antennae at the bottom of the UFO needed to animate at a different rate to the rotation of the UFO itself which meant I needed to split the enemy into two different sprites. Then I thought the pilot looked a bit static and I should try and animate him simply so it looked like he was flipping various controls to steer the craft – this looked rubbish on a loop so I split this out into yet another separate sprite and chose the animation frame randomly rather running on a sequence. It also animates a lot slower than the craft itself. Final touch was to add some particles for an ‘anti-gravity’ type effect.

I could base the motion heavily on the motion for the ‘mother‘ which is one of the reasons this enemy was fairly quick to implement. Every 10 frames the ‘bastard’ samples the player’s location and moves towards it. It’s much faster than the ‘mother‘ and the sampling rate is more frequent which makes it a lot more dangerous! To add a slightly more erratic feel I skip the sampling of the player’s location every three iterations or so.

This straightforward AI worked pretty well but I wasn’t happy with the way the enemy sometimes hovered over the player. I improved this by making the enemy ‘retreat’ when it collided with the player or fired a bullet. It alternates the retreat by flying to the top right, top left or directly above the player. This attack/retreat motion, whilst still pretty ‘dumb’, looked considerably more ‘intelligent’ than simply ramming the player the whole time.

The ‘bastard’ is pretty dangerous – maybe too dangerous. Now I’ve got a few different enemy types in place I think I’m going to have to start working on different weapons and the weapon upgrade system so I can see how these enemies play out against a more powerful opponent. The ‘pistol’ I’ve implemented so far is to be the most underpowered weapon in the game after all.

Dev Time: 1 day
Total Dev Time: approx 59.5 days

previous | next


The Main Character Design – Actually Three Separate Sprites!

mockup_3x
First Draft Of Enemy Motion – A Bit Clumsy

mockup_3x
Adding Attack/Retreat Behaviour. Much Nicer!