Random Class, Singletons, and the “Big Debate”™ (does this sound familiar?)

A few weeks ago I wrote a VERY similar post about my Logger class and the debate over the use of Singletons.

I’ve done the same with my new randomization class, LRandom().  LRandom does several things under the hood, and is a singleton for a very specific reason.  First, I wanted to use it to replace the random class that Dungeon Architect uses during initialization of a dungeon or map.  In part because I wanted more control over randomization, and in part because I wanted all aspects to produce the same values with the same seed.  Previously, at least in earlier versions, DA would produce the same dungeon layout, but things like decorations and extras would not always be the same.

Additionally, I wanted the same random class to be able to control other randomizations during play: loot, die rolls, et cetera.  The current implementation uses a single System.Random instance, though I may extend this to have several – one for dungeon building, one for loot, one for mob AI, and so forth.

Also, the state of the System.Random is stored in a serialized file on exit.  This should, in theory and after a lot more work, allow one to pick up where they left off with the state of the randomizer where it was before.  The main goal here is to prevent “known randoms” with the given seed.  The first chest you run across won’t always have the same stuff.

The class also contains the original DA methods for NextGaussianFloat() and GetNextUniformFloat() to integrate without changing a lot of the DA code.  And lastly, it contains methods that allow the instance to be reseeded if need be, which is mostly good for debugging, but may have benefits during runtime as well.

So, currently, LRandom() and LLogger() are two singletons that I’m using that have proven very beneficial.  If you missed my last post, or want to hear more about Singletons (the good, the bad, and the ugly, so to speak), check out this great podcast from The Debug Log- Episode 73: Design Patterns: Singleton.

How To See Your Player… Making Walls Transparent

Over the past several months working on the Dungeon theme for Labyrintheer, I’ve changed my camera angle several times.  I keep moving it higher to prevent walls and such from occluding the player, but I’m never happy with such an oblique view.  So, over the past few days I’ve been looking at options to make walls transparent when they are between the player and the camera.

Some solutions simply disable the geometry.  This isn’t acceptable for my game, and I suspect for many.  You could accidentally walk backwards out of the playable area, or an errant AI could take a bad turn during it’s pathing and fall off the world.  Plus, disabling geometry just doesn’t seem like an elegant solution.  My primary goal (and I’m still working on it) is to use a shader for this directly, though that seems like it has some major pitfalls (how do you tell a shader about an object other than the one that it’s drawing?).

So, for now I’m cheating with a very small amount of code and an extra material for objects that I want to hide.

Basically, I’ve duplicated the four wall materials I have, and the duplicate materials use transparency with an alpha value of 100.

My player controller script now calculates it’s distance from the camera every frame (though I think this might be able to be done once in Awake() since the distance should be fairly static), like this:

     void Update ()
     {
         GetInput();
         ProcessInput();
 
         distanceSquared = (transform.position - Camera.main.transform.position).sqrMagnitude;
     }
 
     public float Dist()
     {
         return distanceSquared
     }

Then created a script to go on the walls (or any object that needs to be transparent to prevent occlusion), as such:

TransMaterialSwap.cs

 using UnityEngine;
 
 public class TransMaterialSwap : MonoBehaviour {
 
     public Material _original;
     public Material _transparent;
     private GameObject player;
     private playerController pC;
     private Renderer rend;
 
     void Start()
     {
         player = GameObject.FindWithTag("Player");
         pC = player.GetComponent<playerController>();
         rend = this.GetComponent<Renderer>();
     }
 
     void Update()
     {
         if ((transform.position - Camera.main.transform.position).sqrMagnitude < pC.Dist())
         {
             rend.material = _transparent;
         }
         else
         {
             rend.material = _original;
         }
     }
 }

In the inspector I set both the original material and the transparent material.  If the object is between the camera and the player, it switches the object’s material to the transparent material.  It looks like this:

There are a few issues here.  First, I still need to profile this to see if the solution gives my runtime performance a hit.  I don’t suspect it’ll be TOO bad, but it doesn’t hurt to check, especially with larger maps.  I may look into options to only run the check if the object is visible to the camera rather than always checking on Update(), every frame for every wall.  The other issue is that by making it transparent, light comes through.  I’m not sure how big an issue this will be – it’ll require some play testing.  But it may be an issue in some situations.

Lastly, as I said, I really do want to attempt this in a shader.  I figure it’s a good method to learn shader programming, even if exactly what I want isn’t possible.

Logger Class, Singletons, and the “Big Debate”™

So I’ve spent a bit of time working on getting a logger class setup, which is rudimentarily complete.  This class currently just writes out to a file and also to the debug console in Unity.  It takes in a message, a module, and a severity.  I wanted to easily have access to this class from anywhere, but since it writes to a file, I also needed to ensure that there was ever only one instance trying to access the file at a time.  This, of course, led to the singleton pattern.

Now, even a cursory glance through newbie programming blogs and books can cause one to question why this is even a pattern to begin with – it seems that everyone says to stay away from them, and I kind of understand why you don’t want to overuse them.  The Debug Log has a pretty good episode about them here.

So, singleton was the answer, and it was setup nicely enough and it works, though I still need to make it threadsafe.  But… logging:

LOG!
LOG!

So, now it’s back to work on the game itself.  I have most of the systems in place to get a sample level up and running soon.  Yay!

Tryin’ a catch me settin’ dirty

I’ve been working on the core combat mechanics for the past week or two, and have finally got things feeling decent – at least to start with.  I wanted to do something modular so that over time it would not only be easy to tweak, but also easy to add additional features.  So, here’s a sample of what I have so far:

DamagePackageDiagram_v1.0
DamagePackageDiagram_v1.0

The base element here is the DamagePackage, which contains information about the raw damage amount (DamageArray – from each of the 12 possible elements of damage), the cause of the damage (DamageVehicle – e.g., weapon, creature, trap, environment, effect), any damage effects which would include damage over time (DoT) type effects, and any special effects from the attack (chance to be set ablaze, frozen, sleep, silence, etc.).

There is a slight error with the diagram above, as I’m typing this all out – the CharacterStats are brought in on the Talker and Listener levels.

At any rate, the DamagePackage moves to the DamageTalker, which takes in the attackers stats for any modifications, then sends the package along to the DamageListener on the attacked actor.  The Listener works in reverse, unpacking the information from the package, applying resistances and such from the attacked actor’s stats, then applies that modified damage package to the actor itself.

The beauty of this system is it’s flexibility.  The downside is that different components reside on different levels of the actors and their equipment.  For instance, on the player, the stats and the listener are on the root, but the talker and all of it’s constituent parts live on each weapon (or spell).  For a non-humanoid creature, almost everything lives on the root level.  Except listeners – the listener must always reside on the same layer that the collider lives on.  Well, it doesn’t have to, but it makes things worlds easier.  So…  this is something I’m trying to figure out.  Though honestly, I could probably package this up for the Unity Asset store once I get it all cleanly situated.  I’m happy with where it’s at now, but it has a LOT of work still ahead of it to be a nice, simple-to-use package.

DoLevelUp()
DoLevelUp() function

Of course, the system needs to be set dirty whenever an actor’s stats change, or when weapons/armor are swapped out that might impact stats.

On Paper…

Even the most digitally-inclined sometimes have an easier time wrapping their head around ideas on paper instead of a screen. I’m currently working through some logic with my combat system in exactly this way.

{"macroEnabled":false,"qualityMode":3,"deviceTilt":-0.9205247481637677,"customExposureMode":0,"extendedExposure":false,"whiteBalanceProgram":0,"focusMode":0}

Mapping out idea, and sometimes even just writing things down helps me really get a good idea of what I want or need to do – better than typing and seeing it on the screen.  It’s not a bad way to get thoughts out of your brain.

{"macroEnabled":false,"qualityMode":3,"deviceTilt":0.9151561856269836,"customExposureMode":0,"extendedExposure":false,"whiteBalanceProgram":0,"focusMode":0}

{"macroEnabled":false,"qualityMode":3,"deviceTilt":-1.327543258666992,"customExposureMode":0,"extendedExposure":false,"whiteBalanceProgram":0,"focusMode":0}

Often, I’ll jot down a URL to a page that talks about something similar to what I’m trying to do.  I currently have three books.  This lined book is full of notes and charts and drawing and ideas.

I have a grid/quadrille book that has database-like charts and some organized info, and I have a dot-pad book that so far has only a few layout ideas for UI.

It may seen archaic to some, and I typically prefer digital information, but hand-written notes has really helped me break through some of my issues so far in this development cycle.

The Great Stack Exchange and Combat System Code

I assume that most people working on their first (or twentieth) game probably know about Stack Exchange, probably even use it now and then.  If you don’t, I can’t recommend it highly enough.  It’s my go-to place to help me figure out what I’m doing when I get stuck.  GameDev.SE is a great place for game development specific stuff.  StackOverflow is the place to go for code-specific questions that aren’t related to game design or development.

Yesterday I posted a question for a sanity check.  This is the sort of thing that I have to think through several times before getting it right.

If you don’t want to click the link, the short situation is that I’m probably going to have DamageListeners on all creatures that can take information about an attack and process it for the actor.  All damage-causing things (weapons, spells, traps, environment) will have a DamageTalker that processes the information and tailors it to the specifics before sending it to the receiving actor.  In between, a DamagePackage will contain the specifics of the attack.  I’ve debated whether this is overkill or not, but because of some custom damage, DoT, and effects that an attack can apply, I wanted to have a very customizable collection of information about the attack from both sides.

Progress with Tilesets and Map Generation

I posted these images on Facebook a couple of weeks ago, and they somehow never made it here.  After struggling with a few things related to graphics and map/level generation, I feel like I finally broke through the wall that was holding me back.  I started working on character creation, mobs, and am starting to work on some game mechanics finally after months of scrapping attempt after attempt.

I figured one of the core ideas behind Labyrintheer was, well… labyrinths: mazes, dungeons, et cetera.  If I couldn’t get those done right, or at least make some progress toward them, then the rest of it was all for nothing.

image-1-1
A progression of map/level layouts, all randomly generated in one way or another.

This image shows progress on level generation.  There were actually a few iterations that don’t show up here.  I’m not even sure I have screenshots of them.  Maybe at some point I’ll look back and try to find a few.  It really started out with an idea that I wanted to create levels using cellular automata.  And I did.  And they actually were simply too organic.  I made a small, playable game that would randomly generate a new map every time the spacebar was pressed, and would spawn the player in to one of eight edge/corner areas and create a goal that was as far away from the player as possible.

Map generation was very quick, even with large maps, but trying to skin everything immediately made me realize it just didn’t feel right.  At this point, though, I wanted a true top-down 2D game (think Legend of Zelda on the NES).

After that experiment, I started looking at graph grammars and how they could apply to attaching branching groups of pre-made sections of dungeon together.  I started down this road and was using Tiled and Tiled2Unity to import simple square rooms that had varying exits and would connect via those exits (top-left).  The upside to this approach was that maps generated just as fast as the CA map generation, were much less organic, and had order (top-right).  Green rooms came first, then yellow, the red.  After, a purple room was created (boss room) and then all dead ends were capped off (blue rooms).  This actually solved a few problems that I’ll now have to resolve entirely.

The downside to this approach was that it felt TOO inorganic.  Even using a wider variety of rooms and hallways to create a dungeon via graph grammars gave it a feeling of being too symmetrical.  I was able to use that to test some stuff with random placement of torches in a dungeon and allowing that to be the sole source of light (bottom-left).

Still, something new needed to be done.  I decided that an angled view of a 3D world would fix a lot of issues, many of them related to physics, line of sight (LoS) and environments.  I ended up trying, and am currently using, Dungeon Architect with Unity to create the maps (bottom-right).  This has allowed me MUCH greater freedom to customize pseudo-random levels.  So far I’m quite pleased.

Sample of a too-symmetrical, but very large map.
Sample of a too-symmetrical, but very large map.

The next part of my struggle was related to assets.  I presumed there were two options – pay through the nose for an artist to give me custom assets, which is what I preferred, or use free/cheap assets and run the risk of the game looking very similar to other games out there.  Neither of those were great options.

Tileset progression over time.
Tileset progression over time.

The top-left (yeah, very similar to the first top-left, right?) shows some very 8-bit stylings, which would’ve been fine if they weren’t so utterly generic.  I ended up using Photoshop to create the top-right tileset for Tiled when I thought I’d use shape grammars.  It wasn’t too bad, actually, for not being an artist.  Multi-directional blending of regular, light, and dark dirt floors gave me pretty good control to paint tiles as I saw fit within those parameters.  It still just didn’t feel right.

The bottom-left shows some early work (two months ago or so) with Dungeon Architect, some great assets from InfinityPBR that I somehow screwed up royally, and a REALLY bad camera design.  The bottom-right is more or less the current look of the dungeon biome for the game.  I have tons of biomes still to design, and tons and tons of stuff to still bring into the dungeon biome, but I have a good enough playable space that feels and looks “right” that I’ve gone, as I said, into the mechanics of things for a while so that I can do greater play-testing as I move along.

As a note to anyone reading this because they are embarking on their own game development adventure, just because I stopped using some tools or processes does not mean they aren’t great tools.  They just weren’t right for this project.  Tiled is a fantastic tool to design tile-based maps for many, many types of games and can deal with top-down, isometric, and even hexagonal tile systems.  Tiled2Unity is a life saver if you’re using Tiled for a project in Unity, and Sean is incredibly helpful and quick to respond to things.  Cellular automata is… well, it’s just fun.  There’s tons that you can do with it, and making EXTREMELY organic feeling maps is one of those things.  If you’re developing a game that is in caves or other natural systems, give it a shot.  Graph/shape grammars is also really cool, and you can do a lot of different things with it.  In fact, I still might use it for custom weapon creation, and even if I don’t I have another game idea for someday where shape grammars would be a perfect fit.

In the end, don’t be afraid to throw away a few months worth of work because it isn’t working.  Don’t let it get you down, either.  Sometimes that’s just the way of things.  And I had heard it before it happened to me.  It’s different when it is actually happening to you.  Just know that many, many people have been there, too, and great things can come from it.

Material/Texture woes…

I’ve been working with the extremely awesome material generators from InfinityPBR.  However, I can’t quite figure this issue out.  In the demo scene provided with the generators (and sitting inside my staging project), the walls looks great.  When I export them, bring them into my game project and attach them to my walls, they look awful.  So…  now I need to figure out what I’m doing wrong.

In staging:

screen-shot-2016-10-25-at-11-01-06-am

In game project:

screen-shot-2016-10-25-at-11-27-16-am screen-shot-2016-10-25-at-10-25-38-am screen-shot-2016-10-25-at-10-26-22-am

Gelatinous Cubes – Congealing and Melting

As soon as I started understanding BlendShape options for some of these models, I really wanted to dig into programmatically using them for some interesting effects.  First up is a gelatinous cube that starts out melted and waits for a player to get into proximity.  Currently, it only moves to its idle animation, but there will be FIERCE combat eventually.  And not all gel-creatures will start in this state.  Some will likely roam around, hungry for adventurers.  Some might fall from the ceiling with a plop, or squish out of a hole.  And this is just one type of critter that will be around to sway our Labyrintheer from his or her mission.

Big Changes, Small Update

So, after a considerable amount of back and forth, I’ve decided to go with a fully 3D world and a fixed isometric camera.  The 2D method was intriguing, but ran up against a few issues:

  1. Physics in 2D isn’t quite as…  real?  I’m sure 2D physics can be made to feel real to some degree, but our worldly physics exists in a 3D world, and I just wasn’t a fan of the flat feeling.
  2. Art in 2D is harder to make and get made.  This one surprised me the most.  It seems far easier to create and find 3D models and assets than 2D.  It’s even easier to find 3D modelers than it is to find sprite artists.
  3. Partly related to #1, lighting, LoS and other similar bits are much more difficult in 2D (for me, at least).  These things sort of exist naturally in 3D worldspace.  They seem very shoe-horned into 2D.

So, I’ve found some tools and assets that are helping me move this along.  After spending months (literally) trying different methods to create the levels, I’ve settled on a tool crafted by Code Respawn called Dungeon Architect.  It’s a fairly extensible dungeon/level generation tool that is giving me playable spaces out of the box.  Over time I will need to modify the underlying code a bit, but for now it is a HUGE time saver.  If you’re interested in checking it out, they also make a version for the Unreal Engine here.

One of my other struggles was art.  I am not an artist.  I can modify art like crazy, but aside from my past experience as a semi-professional photographer, creation of new art is difficult for me.  That led to a big concern; I could pay thousands of dollars that I don’t currently have to artists to create fresh new content, or I could find cheap, existing assets and have a game that looks like other games that use those assets.  Neither are great options.  Lo and behold, a third option presented itself via the absolutely amazing and customizable assets from InfinityPBR.  Tons of 3D models, materials and substances that are extremely malleable right inside the Unity engine.  The brick wall in the image below is created from their Brick Generator.  The options are incredible enough that I spent an entire evening – literally hours – making, remaking, and fine-tuning a wall just the way I wanted it.  The image below isn’t great (it’s not runtime, it looks better in the game), but it’s a fine example of some of the stuff from InfinityPBR.  The torch is also theirs, with a few particle effects and a point light added for effect.

If you are trying to break into game development and need assets, I cannot recommend InfinityPBR highly enough.  The assets range from US$45-60 each, but each asset isn’t a static thing – it’s a small library of things.  They also offer a $25/package option to pick up every new package (seems like a couple each month) at a HUGE discount the day they come out, before they are available on the Unity store.  Even if you get some assets you might not use now, it never hurts to have a great 3D library, and at that price you really cannot go wrong.

Wood Torch with Particles
Wood Torch with Particles