Adventures in Unity – 2.4 Edge Padding

Official_unity_logo

The levels in this project are made up of tiles – I’d working with about four different tile types to when constructing the basic game framework;

 

TileFloorA
1. Default Floor Tile
TileBonusA
2. Bonus Tile
TileStartA
3. Start Tile
TileGoalA
4. Goal Tile

 

The floor tiles looked great – But the start, goal & bonus tiles were a little out of place & had seams showing;

Seams1

 


 

Googling around, I discovered I wasn’t the first person to have this issue – & everyone seems to have their own resolution…

Some people offered sensible first steps advice, such as ensuring the in the texture setting clamp rather than repeat was selected – Others suggesting ideas like merging the tiles into one model, drawing with a custom shader, deleting all offscreen model faces, recalculating the models normals, turning off anti aliasing, turning off mip-mapping, etc..

After trying, a failing with quite a range potential solutions; what eventually worked for me was edge padding.

Edge padding, as the Unity docs explain;
Unity renders a scene using a process known as downsampling which uses texture filtering to smoothly render the textures. If the ‘gutters’ (blank areas between UV’s) have colors/transparencies that are very different from the colors inside the UV’d areas, then those colors can ‘bleed’ together which creates seams on the model. This problem will also occur when neighbouring UV shells have different colors; as the texture is downsampled eventually those colors start to mix.

To avoid this problem, edge padding should be added to the empty spaces around each UV shell. Edge padding is the process of dilating the pixels along the inside of the UV edge to spread the colors outward, forming a border of similar colors around the UV shell.

 


 

UV Mapping is the process of projecting a texture onto a 3D object – It identifies what area in a texture/image a model faces uses as it’s texture.

So, for example, in the image below the right side shows a model with one face selected (outlined in orange & shaded slightly) .

The left hand side shows the texture being used – The orange square (on the top left quarter) shows what part of the texture will be used to ‘paint’ the select face

UV Mapping 2

 


 

In my case, my original textures looked like this;

TileBasicX1B

My uv texture mapping looked like this;

TileBasicX2B

The problem was the UV areas I’d setup were too tight – so when Unity rendered the textures onto the models, it would sometime collect colour information outside my defined UV area – causing seams to be displayed.

The fix was to reposition the UV mapping & add a border to accommodate the potential bleeding effect.

TileBasicYB
My initial attempt at edge padding resolved 90% of the problem – but I found the enter/exit tiles didn’t quite match up.

Seams2

 


 

For ‘complex’ textures, instead of continuing that edge colour, I instead just continued the pattern.

Instead of using this;

TileBasicYB

I setup the texture to look like this;

TileBasicZB

Which worked perfectly;

Seams3

 


 

Note: My textures & UV mapping are pretty simple- I used that to my advantage when edge padding – padding far more of the texture than I really needed to.

The amount of padding actually required depends on the size of the texture used – (I think the smaller the texture, the higher the chance of seams)- For this game, my textures are 64×64 – I found I needed a 3-4 pixel buffer to completely remove seams.

 


 

Ultimately, edge padding provides a satisfying fix – going forward, as long as I keep padding in mind when creating textures, it should have almost no further impact on this project.

 


Play the game (WebGL)


 

Next post: 2.5b Palette Shift

Last post: 2.3 Palette Swap

Contents page.

 


 

Adventures in Unity – 2.3 Palette Swap

Official_unity_logo

 

I wanted to try using textures based on the original games graphics.

Mainly for two reasons;

  1. Because I wanted to see how it would look – If it works out, I have some low impact textures for the WebGL version of the game – If not, then, at least I’ll still have reason #2.
  2. I thought they would work well as placeholders – until this point, I’d just coloured different tile types different colours – & while that’s fine when I only have 2-3 types, once the numbers start stacking up it’s going to get confusing remembering which tile colour has what effect – Using the original graphics as placeholder textures ensures they’ll look unique & easily distinguishable – It’ll make it faster & easier when trying to see how the original game works and feels against my implementation – & makes creating the textures much easier & far less time consuming.

However, since I never seem to like making anything too easy for myself, I decided to create textures based on both the C64 & Spectrum versions of the game.

 


 

The Sinclair ZX Spectrum 48k handled graphics in a rather ‘unique’ way- The 256×19 screen was broken down into 8×8 pixel blocks – Each block can display two colours at any one time – background & foreground (paper & pen)

While this architectural design caused lots of headaches when developing video games – With bounder, it allowed the developers to base each level on a different colour pair – so they could use the same base graphic for each tile type – But by changing the colours used to draw the tiles, it gives each level a distinct feel.

Effectively palette swapping. As Wiki explains;

A palette swap is a practice used in video games, whereby a graphic that is already used for one element is given a different palette, so it can be reused as other elements. The different palette gives the new graphic another set of colors, which makes it recognizably distinct from the original.

 

PaletteSwappedA1

 


 

After a quick google I figured I had three options for replicating the spectrum level  based palette swap;

  1. Use a different texture for each level. This, given my requirements, would be the quick to implement, be low on systems resources and could be implemented cleanly.
  2. Write a shader to swap the colours at runtime – Another sensible, relatively easy option – & since I’ve yet to play around with shaders in Unity it would have been a useful intro.
  3. Edit the textures and change their colours at runtime – When I’ve tried this sort of thing in the past, it’s usually come with a huge processing overhead – impacting game performance needlessly – probably the worst option of the three.

 

I went for approach #3.

 


 

With this game, palette swapping is pretty straight forward;

The projects textures contains a maximum or four colours; black, white, green and blue (most only contain black & white) – e.g.

TileGoalLSpectrum

Since there are so few colours, all of which are known beforehand, identifying and swapping is pretty simple.

The code provided below is specific to this,simple colour swap – but should be easily modifiable to accommodate more complicated requirements.

 

PaletteSwappedStartA1

 


 

First we need to make the original (source) texture read/write enabled. This is so we can run though the texture and read the colour of each pixel. This can be done within the Unity IDE in three steps.

1 In the ‘project‘ tab, select the texture you want to use;

TextureAdvancedA

 

2. In the ‘inspector‘ tab, change change the texture’s ‘Type‘ to ‘Advanced‘.

TextureAdvancedB

 

3 Next, put a tick in the read/write enabled check box.

TextureAdvancedC

 


 

Now the ‘source’ texture is ready, we need some code to perform the swap.

I’ve written two methods for swapping the colours -Both are displayed below – There’s not a lot between them – cut & paste whichever one you prefer.

 

Method 1:

Based on the code provided by Scribe in answer to a palette swap question on the unity community answers

This method requires a source texture (the read/write enabled texture created earlier) and an array of colours – These are the level specific colours which will replace the source colours.

It copies the textures pixels into a Color array – Then loops through the color array, checking the colour of each pixel and replacing as required.

Once all the colours have been checks & changed, it sets the image into the destination texture & importantly calls Apply() to save the updated texture.

Texture PaletteSwap(Texture2D source, Color[] toColours) {

     //Renderer rend = GetComponent();
     //Texture2D source = rend.material.mainTexture 

     Texture2D destination = new Texture2D(source.width, source.height);

     //---

     Color[] pixels = source.GetPixels(0, 0, source.width, source.height);

     int pixelsLength = pixels.Length;
     for (int counter=0; counter< pixelsLength; counter++)
     {

          if (pixels[counter] == Color.white)
               pixels[counter] = toColours[0];

          else if (pixels[counter] == Color.black)
               pixels[counter] = toColours[1];

          else if (pixels[counter] == Color.green)
               pixels[counter] = Color.black;

          else if (pixels[counter] == Color.blue)
               pixels[counter] = toColours[2];

     }

     destination.SetPixels(0, 0, destination.width, destination.height, pixels);
     destination.Apply();

     //---

     //rend.material.mainTexture = (Texture)CopyTexture2D((Texture2D)rend.material.mainTexture);
     return (Texture)destination;

     //---

}

 

Method 2:

Based on code provided by CarterG81 in answer to a palette swap question on the unity community forums

This method uses two while loops (y & x)  to get the coordinates of each pixel in the source texture in turn – It then checks the retrieved pixels colour against the swap list – writing the replacement colour directly onto the destination texture.

Once the loops complete, it calls the all important Apply() method to create the new destination texture.

Texture PaletteSwap(Texture2D source, Color[] toColours)
{

     //Renderer rend = GetComponent();
     //Texture2D source = rend.material.mainTexture 
     Texture2D destination = new Texture2D(source.width, source.height);

     Color pixelColor;

     int y = 0;
     while (y < destination.height)
     {

          int x = 0;
          while (x < destination.width)
          {

               pixelColor = source.GetPixel(x, y);

               if (pixelColor  == Color.white)
                    destination.SetPixel(x, y, toColours[0]);

               else if (pixelColor  == Color.black)
                    destination.SetPixel(x, y, toColours[1]);

               else if (pixelColor  == Color.green)
                    destination.SetPixel(x, y, Color.black);

               else if (pixelColor  == Color.blue)
                    destination.SetPixel(x, y, toColours[2]);

               else
                    Debug.Log("Color.r: " + source.GetPixel(x, y).r + "  Color.g: " + source.GetPixel(x, y).g + "  Color.b: " + source.GetPixel(x, y).b);

               ++x;

          }

          ++y;

     }

     destination.Apply();

     //Apply the texture to the material
     //rend.material.mainTexture = (Texture)CopyTexture2D((Texture2D)rend.material.mainTexture);
     return destination;

}

 

The colour swap list is defined in a cheesy little method which, when passed the current level number, returns a array colors for that level;

 

Color[] LevelColours(int inLevel)
{
     switch (inLevel)
     {
          case 1: return new Color[] { Color.white, Color.black, Color.magenta };
          case 2: return new Color[] { Color.yellow, Color.blue, Color.magenta };
          case 3: return new Color[] { Color.cyan, Color.red, Color.cyan };
          case 4: return new Color[] { Color.cyan, Color.black, Color.red };
          case 5: return new Color[] { Color.green, Color.black,Color.white };
          case 6: return new Color[] { Color.white, Color.red, Color.blue };
          case 7: return new Color[] { Color.yellow, Color.red, Color.white };
          case 8: return new Color[] { Color.white, Color.black, Color.yellow };
          case 9: return new Color[] { Color.yellow, Color.blue, Color.white };
          case 0: return new Color[] { Color.cyan, Color.red, Color.blue };
          default: return new Color[] { Color.red, Color.yellow, Color.white };
     }
}

 


 

PaletteSwappedGoalA1

 

& that’s it.

I’m currently swapping the texture palette every time I instantiate a new tile – & while It seems to work with no noticeably slowdown/jerkiness, it’s impractical as a long term solution.

My next step will be to instantiate everything at the beginning of the level…

  1. Once the level data is loaded, identify which tile types will be used for the level,.
  2. Load the the textures for the identified tile types – change their colours and store in an object.
  3. Now, when instantiating a new tile instance, I attach the relevant pre-cooked texture.

 


Play the game (WebGL)


 

Next post: 2.3 Edge Padding

Last post: 2.2 Framework

Contents page.

 


 

Adventures in Unity – 2.2 Framework

Official_unity_logo

 

I’m repurposing project 1 for this game – rather than starting from scratch and reusing elements I’m editing the existing code – which is never a good idea; but one I find hard to resist.

I wasn’t completely happy with the game structure with project 1 & wanted to take a stab at reviewing and updating – Hopefully improve things a little. The new version isn’t perfect, but I think it’s an improvement.

It’s based almost entirely on using enums to define ‘states’, managers to switch between states (e.g. GameStateManager & GamePlayManager) & elements which implement different code/functionality depending on the current state.

I’ve outlined each class/element in a bit more details below;

 


 

GameStateManager: As with Project 1 (Block Runner) – The game state manager looks after the top level game state – That is, are we on the title screen, highscore screen, playing the game, etc… Top level GSM stuff. It’s still overloaded; but I’ve begun simplified things a little – Game Over is now managed by GamePlayManager (though at the end of a game the GameStareManager still checks to see if the player has a new highscore).

GamePlayManager: Looks after the game state ‘in-game‘ – It’s concerned with things like; initializing the level, displaying the level intro message, playing the game, displaying end of level messages & handling gameover, etc.

Player: Modified from Project 1‘s player class – This is looks after the current state of the player – Are they entering the level, or exiting, playing the game or have they fallen off a tile? It also managers the player input and updates player input accordingly.

A notable aspect is the way player deaths are handled – Once a player is killed, the Player class looks through all the current tiles on screen and identifies all safe/standard tile types (only checking against the top half of the screen) – It then randomly chooses one to be used as the spawn point for the player re-entering the level. If there are no safe tiles currently active, the level will continue to scroll until a safe tile becomes available.

TileManager: Based on the ‘PlatformManager‘ class from Project 1 – Unlike the classes above, this isn’t managed by state/enum.

Each level is made up of tiles – Tiles create the path the player must travel through in order to reach the end of the level. It’s the environment the player exists in while playing the game – The meat of the game.

There are lots of different types of tiles used in the game – e.g. normal/standard tiles act like platforms in a standard platform game – players can safely bounce onto/off-from them as often as they like – Arrow tiles allow the player to bounce twice as far (avoiding obstacles or large gaps in the level), walls block the players path, lava tiles kill the player on collision etc…

The TileManager class manages these tiles – Instantiating, positioning, scrolling and ultimatly destroying tiles.

For the tiles themselves, I’ve followed the example given in the Space Shooter demo code – Each tile type is defined as a prefab; these are plugged into the TileManager class as generic GameObjects – This allows me to easily manage the tile types with the TileManager class, whilst allowing each tile to maintain it’s own personality.

At the start of each level, the TileManager class loads a (text) map of that level. It uses this map to populates a two-dimensional array of GameObjects (Tiles) – This builds the level.

Since levels can be pretty large, so I don’t want to have ALL the tiles instantiated & active at one time – It’ll soak up far too much memory. So the array only holds the tiles which are onscreen at that time (with a little offscreen buffering to smooth things out).

Each loop TileManager updates the position of each tile in the array – scrolling them down the screen – Once a row has moved off the bottom of the screen; TileManager reads the next line from the level map; populates the offscreen row with the new tiles & repositions them at the top of the screen, ready to scroll down and confound the player.

Scoreboard: Currently still fairly undefined – The relevant fields are in place (score, hiscore, lives, jumps) – & I’ve started hooking them up to the game code – But I’m not particularly happy with the way it currently looks in game – So I’m intending to finish connecting to the game data (hiscores are proving a pain) – But then leaving all the heavy lifting (animations, transitions, etc) – Until I decide how I want it to actually work.

 


 

There’s a couple of important areas still undefined; the background & enemies.

Background: On the C64 version of the game the background seems to be created out of tiles (as with the top layer) with generic grass, mud, water type images – Using parallax scrolling to give the impression of depth.

Enemies: From what I can gather enemies in the original bounder are made up of two classes/types;

Type 1. Enemies which operate in the expected manner – moving around the screen, needing to be avoided by the player.

Type 2. Enemies which sit on tiles, acting either as one-touch kill obstacles – or in a more esoteric manner e.g. warp enemies, which, upon collision, transport the player to another (safe) part of the screen.

With my current setup, I’m more inclined to class type 2 enemies as tile types.

Though I’m intending to wait until I’ve setup a wider range of tiles before I consider this further.

 


 

A short video demonstrating the current framework…

 

 


 

For now that’s it.

For my next step I’m intending to start defining & adding tile types to the game – getting their functionality defined & making them look a little more interesting/unique.

So, first I need to figure out what different tile types there are & how they operate.

Below is a quick video demonstrating how things are at the moment

 


Play the game (WebGL)


 

Next post: 2.3 Palette Swap

Last post: 2.1 Introduction

Contents page.

 


 

Adventures in Unity – 2.1 Introduction

Official_unity_logo

My second project with unity.

For this, I decided, rather than expanding project 1 (something I’d like to do in the future) – I’d write a completely new game.

I wanted something a little larger – But still keeping the scale ‘reasonable’ – So I can learn & play while I develop.

Eventually setting on a remake of ‘Bounder‘ – a Commodore 64 game released by Gremlin Graphics in 1985.


Bounder_c64_cover


The cassette inlay explains;

Move Bounder ( tennis ball ) around screen, bouncing on hexagonal
slabs only.  If you miss, you fall to your death. Be sure to
identify mountains and walls as you can't go over them, you must
go around. Any collision means you lose  a life.

As a rule: IF IT ISN'T HEXAGONAL, THEN AVOID IT!

(Note – slabs are in fact rectangular with a hexagonal design)


This long play video demonstrates C64 gameplay;


It’s worth noting that Urbanscan a company owned by Ian Stewart (one of Gremlin Graphics founders) – Has released a new version of Bounder on the app store.


Putting this together, I’m intending to try and re-use projects 1’s structure\GSM – maybe tidied & tightened a little – Which will hopefully allow me to focus more on the game itself.

Ideally I’d like to build a more conservative version first – which I can release as a WebGL game. Which I can then expand upon to create a PC version – Allowing me to add 3D models/animations, more involved shaders, etc… Stuff I havn’t really implemented so far… Also allowing me to setup & try out the type & range of configuration options PC gamers expect to see.


Rather than updating every week – This time I’ll try to update every milestone (working on this part time this will more time between blog entries; but hopefully they will be more meaningful when I do publish them).

Lets see how this goes 🙂


Play the game (WebGL)


Next post: 2.2 Framework

Contents page.