Digging in the Sandbox
  • Slopes and wedges

    Here’s what I’ve been up to over the last couple of weeks.  I’m still working on the company set up stuff, it’s unfamiliar territory for me, so I had to do a bit of research and get advice from some people.  I won’t bore you with the details, but it seems there’s no getting around the complexities that require both an accountant and lawyer.  This is going to cost me a lot of money, so I want to be sure before going ahead with it!

    Upcoming demo

    I’ll upload the demo update as soon as the company is sorted (should be soon now), but in the meantime, here’s a sneak peak at the changes that will be in it:-

    • Improved builder tool controls and usability:-
      • Changed alignment and attachment indicators for improved visibility and clarity.
      • Improved part selection (restricting selection location to where part can be attached).
      • Better selection rotation behaviour during alignment.
      • Improved part resizing response to key presses.
      • Added part resizing indicator to show available resize directions.
      • During alignment attachment indicators are now shown for any attachments that will be created.
      • Selected construction can now be frozen in place during alignment.
    •  More user configurability:-
      • Configurable key bindings for the various actions in the game.
      • Replaced single graphics “quality level” setting with individual settings for more fine grained control.
      • Added many other options (such as mouse look sensitivity and invert, camera FOV, etc.)
      • Improved sound options (volume controls and speaker configuration).
    • UI improvements:-
      • Improved screen layouts and UI elements.
      • UI is now scaled based on screen resolution.
      • New part and attachment info UI overlays.
      • New game stats UI overlay.
      • Improved in-game context sensitive hints.
    • Updated and improved parts:-
      • Improved part behaviour key binding.
      • Differential gears now have limited slip behaviour, with tweakable “slip limit strength”.
      • Lights can now (optionally) have a key bound to switch them on and off, just like motors.
      • Beams now resizable down to 1 unit in length, and plates from 1x1 to 25x25 units in area.
      • Better wheel friction behaviour.
      • Increased max spring rate and damping values for spring dampers.
      • All part models (except wheels) now textured.
      • New light parts (now with paintable lenses).
      • New seat models (replacing old ones).
      • Wheel rims now paintable.
    • Rendering changes:-
      • Construction materialise / dematerialise effect.
      • Part paint application fade in / out.
      • Corrected part paint colour (de-gamma’d, it now visually matches colour shown in UI).
      • Upgraded time-of-day system.
    • The construction frozen state is now saved / restored from saved games.
    • New and improved sound effects (toolbox, footsteps, ambient loop).
    • Minor tweaks to desert proving ground map.
    • Bug fixes.

    As usual I’ve updated any parts that were already in the demo, but I’m not adding any additional ones, all the new parts I’m making are for the full game only!

    Slopes and wedges


    On the subject of new parts, I’ve now implemented resizable sloped beams and plates, as well as resizable wedge plates.


    Designing their shapes was a bit of a challenge because I had to find a compromise between these three competing requirements:-

    1. Be easily representable by box colliders for efficient physics.
    2. Have plenty of room for attachment points.
    3. Look good when combined with other slopes, plates, etc.

    The wedge shape was the trickiest to represent with box colliders.  I contemplated using a convex mesh collider for it, but I wanted to avoid this as they are generally less efficient for physics, and I also have part intersection tests in the game that only work for primitive colliders.  So instead I created a system to dynamically add box colliders, three for the wedge edges, and then recursively adding more to fill in the wedge interior (the larger the wedge, the more interior colliders are needed).  An example of this can be seen below.


    All resizable parts in GearBlocks use procedurally generated meshes, so I had to implement mesh generation for these new slope and wedge parts.  This wasn’t too difficult but did require a fair bit of refactoring of my procedural mesh system to allow for these more intricate shapes.

    Here’s a comparison of the Desert Buggy construction, the original version vs. one I made using the new slope and wedge parts.


    Not only does the slopes and wedges version look way better, it uses nearly 50 fewer parts than the original!

    In the future I want to add a compound sloped plate (i.e. a “corner” piece), as well as curved beams and plates.  The trouble is, the colliders for these will be even more tricky to set up.  I might need so many box colliders to represent these shapes that it wouldn’t be practical, so I may well have to resort to convex mesh colliders for these.  Anyway, something I’ll come back to later.

    Construction interface problems

    The sloped plate part is the first part in the game that is resizable along all three axes.  Unfortunately this particularly highlights the awkwardness of the current part positioning and resizing interface.  I’m not sure what I’m going to do about this yet, but I think I’ll have to revisit the construction controls yet again.  There has to be a way I can make this better, but I’m just not seeing it right now!

  • So where is that demo update already?

    So, um, that demo release I’ve been promising, where is it you might ask?  The good news is, it’s ready to release (has been for a while actually).  The last thing was to set up an installer for it and that’s all done now (if you’re wondering, I used Inno Setup for this, found it a super easy tool to use, with great results!)

    Unfortunately, I can’t release it just yet as I’m still working on getting my company set up.  This is turning out to be more complicated and expensive than I first realised.  Incorporating the company itself is easy, but because I’ve already been developing GearBlocks for a while, I’ll need to transfer GearBlocks IP to the company, which complicates things and adds to the cost (accountant fees on top of the lawyer fees!)  Anyway, I’ll keep plugging away at this and hopefully get it done in the next week or two.

    In the meantime I’ve been adding more parts - some new sliding rack gears with integrated ball joints / hinges (makes for neater steering systems), more lights, and a seat.  I’ve also implemented limited slip functionality in the differential gear, with configurable “locking strength”, should keep that wheel spin under control!

    I plan on adding various types of sloped / curved beams and plates to the game, this will make constructions look a lot better (and save on the number of parts needed in a lot of cases).  Next week I’ll start work on what should be the simplest of these, a resizable sloped beam.

  • Wheel physics revisited

    Last week I decided to take another look at the wheel physics implementation, in particular the tire friction model.  First let’s quickly recap how the wheel physics works in GearBlocks.

    Wheel physics recap

    Every update I find the contact point on the ground directly below the wheel and position a configurable joint there.  This joint is then connected to the wheel at the closest point on its outer edge to the contact point on the ground.  The joint has a linear limit set up to prevent the wheel going below the ground, which provides the wheel to ground collision response.

    For friction between the tire and ground, I set up the configurable joint’s velocity drive to constrain the wheel’s velocity at the contact point to zero, with the maximum force on the drive being set to the friction force.  To calculate the friction force, I use a method inspired by the Coulomb damping model, where the friction force equals the product of a friction coefficient and the normal force at the contact point (i.e the force preventing the wheel from sinking into the ground).

    Previous tire friction hack

    To find the normal force I need to know what force the configurable joint’s linear limit is applying to keep the wheel above the ground.  However, it used to be that in Unity there was no way to access this (even though it was available in PhysX), so I had to estimate the normal force by taking the total mass of the construction, dividing it by the number of wheels, and multiplying it by the acceleration due to gravity.  Basically a total hack, because it assumed the vehicle’s weight was always distributed exactly evenly over each wheel.

    Improved tire friction

    Well the good news is it turns out that fairly recently the joint force was made available in Unity (via Joint.currentForce), so I’ve now switched the implementation over to use this to find a proper normal force.  This means that in a vehicle, weight distribution now affects tire grip, and because the normal force is now being calculated dynamically, weight transfer also affects grip in the way you’d expect, which is pretty cool.  This all sounds great, and is a definite step in the right direction, but there’s a problem.

    Formula magic

    By using Coulomb damping I’m effectively assuming that tires are rigid (i.e. non-elastic) which of course they’re not.  In reality a tire’s grip changes depending on how much it is sliding across the ground (tires actually develop peak grip when sliding slightly).  Not only that, the longitudinal (forward and back) and lateral (side to side) grip of a tire behaves slightly differently.  So most driving simulations instead use some form of “friction curves”, equations that you plug slip amounts into and get friction forces out.  The industry standard is the Pacejka tire models, sometimes known as “magic formulas”, these are empirical models that have been made to fit real world measured data, the equations themselves don’t have any basis in real physics as far as I can tell.

    Sounds simple enough, so why not use the magic formulas?  Well, after looking into this for a bit, I can see several problems:-

    1. The equations for the Pacejka curves themselves are complicated and have a ton of tuning parameters, something I’d prefer not to have to deal with.  Probably overkill for what I need anyway.
    2. The slip values used to lookup into the curves are actually slip ratios.  The upshot being that at low velocities numerical instability becomes an issue (and at zero velocity you’ve got a divide by zero - the slip ratio is undefined!)
    3. Because you need to evaluate longitudinal and lateral slip separately, there’s the question of how to combine the resulting separate friction forces.  You can’t just add them together because a tire can only develop so much grip at any one time, the more longitudinal grip you “use up”, the less lateral grip is available, and vice versa.  This effect is sometimes known as the tire’s “traction circle”.

    I’m sure there are ways around all of these problems.  The Pacejka equations could be substituted with something simpler for example, and I’ve seen various ideas out there that attempt to properly combine longitudinal and lateral slip.  The slip ratio numerical instability issue I’m less sure about at the moment, apparently a lot of driving sims switch to another simpler friction model at low velocities to get around it, seems a bit hacky though.

    Another related issue is that I’m not even differentiating friction levels between different surfaces (e.g. tarmac vs. dirt) yet, so perhaps a realistic tire friction model isn’t worth it at this point?  Anyway, something to keep thinking about and revisit again in the future.

  • Construction controls (again), and props

    Selection points

    Over the last few weeks I’ve been working on fixing something with the construction controls that’s been bugging me for ages.  I wasn’t happy with the range of positions at which you could select a part, you could select it anywhere within its bounds, which wasn’t really restrictive enough.

    Here’s an example.  You could select anywhere on a wheel, even though it only has one point that can attach to anything.


    Much better to restrict the selection point to always be at this attachment point as shown below, that way it feels more natural when attaching the wheel to another part.


    This next example is even worse.  You could select anywhere on a seat, and then translate it so that the selection point was completely outside the seat which is just plain stupid.


    So now I restrict the selection point to be somewhere in the region on the bottom of the seat where its attachment points are, so you always have it selected in a suitable place ready to attach to another part.


    To accomplish this I had to rework some code so that it now automatically calculates the selection region based on where all the part’s attachment points are located.  The upside to this was that I could do away with explicitly specifying the allowed translation directions on each part.  The less I have to manually setup per part the better!

    I also had to implement some new math functions to find the closest point on the part’s selection region to the player’s eye “ray”.  Took a while to do, but it’s never a bad thing to add more stuff to my math toolkit I suppose, could come in handy for other things in the future.

    All this took way longer than I expected, it was only supposed to be a couple of day’s work, sigh.

    Prop parts

    I’ve also added some new “prop” parts.  Props are a new category of part that are the simplest objects in the game, they don’t have a behaviour and they don’t attach to any other part.  The idea is that they can be used with the machines and vehicles you build or placed in the world to set up a scene to play in.  For example, traffic barriers could be laid out to form a race track, the ball could be used in a Rube Goldberg machine.


    As with all the other parts, I’ll be adding more props as I go, any suggestions for these are welcome!

  • …and here’s a video of the tractor. It could do with some proper wheels and the steering would work better with the ball & socket connectors, but I was limiting myself to parts available in the demo.

  • photo from Tumblr

    Playing around in GearBlocks today, built an old tractor with working piston engine & push rod steering.

  • What's in a name

    Gah, I can’t believe it’s been a month already since the last blog post!  It’s been a frustrating time to be honest.  I’ve been planning on setting up a company for a while, to put GearBlocks on a more official footing (it’s something I should have done a long time ago really).  The trouble is I’m having a hell of a time trying to think of a name for the company (all the ideas I’ve come up with seem to be already taken)!  It seems ridiculous that a relatively trivial thing like this is holding me up, but hopefully I can figure it out soon and move on.

    In the meantime I have made some progress with the game though.  The Unity 5.6 upgrade is now done, the rendering issues I was having weren’t too bad to sort out in the end.  Also, I was tired of having old placeholder part assets still left in the game, so I’ve finally removed / replaced / reworked the last of these.

    These are the new seat models I’ve made so far, I plan on adding more types & variations of seat later (any suggestions welcome!)


    Here are the new lights (again, at some point I plan on adding more styles / types of light).  Their lenses are now paintable, so you can have any colour lights you like!


    It was a small change to make the wheel rims paintable too, so I decided to do that while I was at it.


    Well, the next demo release is pretty much ready to go now, it’s just waiting on me getting the company set up, as I want to have that all sorted first!

  • Controls, configuration, and more

    Here’s just a brief update on what I’ve been up to over the past few weeks.  Most of the work has been focused on further improving the usability of the game (better UI, controls, customisation, etc.)

    Construction controls improvements

    I’ve redone the part resizing input code so that now when you press a resize key it responds immediately (before it was kinda sluggish to respond).

    I’ve also made a tweak so that you can now freeze the selected construction in place while aligning to another construction, this can be useful to check positioning and so on before committing to attachment.

    Configurable key and mouse button bindings

    The main thing I’ve been working on recently is a complete overhaul of the input system.  You can now fully customise key (and mouse button) bindings to the various actions in the game.  There’s now a new tab in the controls settings where you can set this up.  You click the button for the action you want to configure, it’ll then wait for a key press, that key then getting bound to the action.


    I’ve also modified the player controllable parts (e.g. motors) that have configurable key binding to work in the same way.  This means you can now bind any keys to them, not just letters and numbers.

    The only thing still left to do here is to allow configuration of joystick / controller inputs, something I’ll revisit at a later date.

    Improved graphics settings

    The other customisation improvement I’ve made is to the graphics settings.  I’ve done away with the (vague and too high level) “quality settings”, and set up proper options that’ll give you more fine grained control when configuring the graphics quality vs. performance of the game.


    Other things

    Some other bits and pieces I’ve also done:-

    • More UI design tweaks and improvements.
    • Better audio mix, updating sounds, etc.
    • Various bug fixes.

    I’m working hard on getting another demo release out so that you can try all this new stuff out.  Unfortunately there always seems to be something that gets in the way!  Currently I’m in the middle of upgrading to Unity 5.6 which has broken some rendering stuff, so that’s what I’m working on right now, hopefully I’ll get this sorted soon.

  • Another ingenious GearBlocks build from Marra92!

  • Another awesome user creation in GearBlocks, a flight simulator!

  • Cool player creation, a cable car in GearBlocks.

  • More UI things

    Over the last couple of weeks I’ve done some more work on the in game UI.

    I’ve removed the old text overlay that showed the name of the highlighted part, as it was positioned near the cursor and kind of in the way.  Now I have a new overlay in the bottom right corner that shows not only the part name, but other details such as its mass, whether it’s paintable or resizable, and info on its behaviour status.


    I’ve also added a similar overlay for when you’re hovering over an attachment in a frozen construction.  It displays the available attachment types that you can cycle between (highlighting the current attachment type), and it’ll also show info on other things like attachment integrity (if damage is enabled).


    During part resizing, rather than add yet another UI display to show which keys to use to resize in each direction (as I was originally thinking), I decided instead to just colour code the relevant parts of the hints text.


    Finally, to help the new UI elements fit, and clean up the look of the UI generally, I’ve also made the whole thing scale based on the screen dimensions.  This means that (in full-screen mode), the UI elements appear the same size regardless of the screen resolution.  I think this is a big improvement, especially at lower screen resolutions.

  • Dev update

    OK, time for a long overdue GearBlocks progress update.  As I’ve mentioned in previous posts, I wanted to improve the construction controls, to try and make them a bit more approachable and accessible, and this is what I’ve mostly been working on over the past couple of months.

    Failed ideas

    I wanted to explore some new ideas in an attempt to improve part positioning and alignment, and also part resizing.

    So I tried making a prototype of a “snap to” grid aligned to the overall frozen construction (instead of to the currently highlighted part as it is now).  While the player is positioning the selected construction ready for attachment, I had a 2D planar grid aligned to the frozen construction that the selection snapped to at unit intervals.  The player could then move this plane up and down along its normal (also at unit intervals) using the mouse wheel, thereby allowing snapped positioning in full 3D space.  There would also need to be some provision for snapping to half unit intervals, although I didn’t get that far with it.  This seemed promising initially, but what killed the idea for me in the end was the realisation that (unlike the current system) it doesn’t easily allow for attachment at arbitrary angles, everything has to be aligned at 90 degree intervals relative to the frozen construction.  At least I couldn’t think of a practical way around this, and I certainly didn’t want to make it less flexibile than what I already have.

    As for part resizing, I thought about separating it out into another tool (with handles that you drag around to resize the part), but not only is this more complicated to implement, I actually think it would be less convenient to use.  Every time you want to resize a part you’d have to deselect it, switch to the resize tool, do the resizing, switch back to the builder tool, and select it again.

    So in the end I decided against making any radical changes to the current construction controls, and instead focus on improving what’s already there.  Let’s go over the changes I ended up making.

    Construction alignment

    One issue with positioning parts is that the alignment grids aren’t always easily visible.  Also, because they’re drawn on top of the parts themselves, it sometimes makes it hard to tell which parts are in front of each other, or even which part you’re about to attach to.  So I changed the grid textures to make them clearer, and modified the shader to fade them out slightly where drawn “behind” objects.  You can see the difference between the old and new grid below.


    Another problem is that when you’re aligning parts together, you don’t know where the individual attachments will be created.  So now during alignment, indicators are shown for the attachments that will be created, an example of this is shown below.


    Lastly, rotating the selected construction can be kind of awkward at times, and I wanted to see if could improve this in any way.  I tried making the rotation be limited to one axis at a time during alignment, and that turned out to help a quite lot because it prevents “drift” away from the player’s intended rotation.

    Part resizing

    One of the main problems with the current resizing controls is that they’re non-obvious, particularly to new players, because there’s nothing showing them what to do.  As a first step towards improving this situation, I’ve now added a resize indicator that shows the available resizing directions (colour coded for the horizontal and vertical directions).


    I’m also going to add a new tool UI display that (among other things) will show which keys to use to resize in each direction.  Hopefully both of these changes together will make resizing a bit clearer for the player.

    Attachment indicators

    The attachment indicators also suffered from not being very visible a lot of the time, so I modified their textures too, and also tweaked them to ensure visibility from all angles.  Here’s an example showing before and after these improvements.


    Other improvements

    I’ve also worked on several other bits and pieces, for example:-

    • More user settings (such as mouse sensitivity for selection translation and rotation).
    • Better in game context sensitive hints.
    • Lights can now (optionally) have a key bound to switch them on and off, just like motors.
    • The construction frozen state is now saved / restored from saved games.
    • A whole bunch of bug fixes (many of these you guys found and reported back to me, so thank you!)

    Next up

    I’m fairly happy with how things turned out after the changes I made, yes the construction controls could still be better, but they’re acceptable, and at this point I need to move on to other stuff really.  There are one or two more small tweaks and bug fixes to do, but apart from that I’m done with the controls and ready to tackle the next thing.

    I want to get another demo build out fairly soon, but I still have a laundry list of small tasks to sort out before I can do that, so those are what I’ll be looking at next!

  • I’ve been playing around with a translucent PBR shader in GearBlocks over the weekend. It’s “paintable” like other materials except the paint colour is used as a tint. Should work nicely for glass, transparent plastic etc!

  • Happy New Year!

    Well, 2016 has certainly been, shall we say, an “interesting” year!  Perhaps many people will be glad to the see the back of it, but somehow I’ve a feeling 2017 won’t be any less eventful.  Anyway, here’s hoping the new year brings good things to you all!

    Back in my little GearBlocks corner of the world, in many ways things have progressed pretty well this year, getting through the Unity 5 hurdle was definitely a big step forward.  I’m a bit frustrated to not be further ahead with the game generally by now though.  I’ll just have to keep chipping away at it, it’ll get there eventually.  I’m very appreciative to all those of you who have played the demo, built some amazing creations, and given me really useful feedback.  It helps motivate me to keep going!

    Over the past couple of months I’ve been working on a bunch of different things.  I was looking at improving the construction controls, but kinda got stuck with “designer’s / programmer’s block” if you can call it that.  So while thinking on this some more, to keep progress going I did several other smaller tasks:-

    • Made a load of new parts (gears, control wheels, suspension parts, connectors and more).
    • Added more user settings (e.g. mouse look sensitivity and camera FOV).
    • UI tweaks.
    • Rendering effects.
    • Unity upgrade.
    • Bug fixes.

    Next week I plan on going back to the controls improvements, mustn’t procrastinate any longer!

  • Something a bit different in this video, just a brief demo of a fun little rendering effect I’ve been messing around with. It doesn’t work properly with all the parts because they don’t all have UVs yet, but other than that I’m pretty happy with it.

  • As promised, here we are showcasing some more awesome builds from the GearBlocks community, thanks everyone!

  • Here are some of the amazing constructions you guys have built in Gearblocks over the past year or so!  Big thanks to everyone who has played the GearBlocks demo and built such cool stuff!  I couldn’t fit everything in one video, part 2 will be coming soon…

  • Dev update

    It’s been a while since the last update, so I thought I’d do a quick post on what I’ve been up to!  A couple of weeks were taken up with travelling back to the UK for a bit, and I was sick all last week which took me out of action unfortunately.  I have been working on the game though over the past several weeks…

    First person controller

    The current first person camera controller in the game is basically a prototype implementation.  It’s buggy and missing a lot of features, for example: camera smoothing, crouching, head bob, and so on.  My plan was to switch over to the excellent UFPS from Opsive (available on the Unity asset store: which has all these features and more.  Unfortunately that didn’t work out, mainly because I couldn’t bring across only the code I wanted from UFPS (character and camera controller) without either modifying it or also including a lot of other stuff I don’t need (e.g. inventory, weapons, damage etc.)

    I think UFPS is great as a starting point for a first person game, but trying to integrate it in at this late stage of a project probably isn’t practical.  So now my plan now is to keep what I have and gradually improve it, probably stealing code from UFPS as necessary!

    Deprecated networking API

    I have a rudimentary networked multiplayer mode for GearBlocks, and in fact even the single player mode runs through the same code paths.  I want to keep this working so that I have a good starting point should I wish to revisit multiplayer in the future.  Right now I’m using the old Unity networking API, which was causing a bunch of annoying “obsolete API” compiler warnings, because it’s recently been deprecated in favour of their new system, UNET.

    I looked into what it would take to upgrade to UNET, using their high level API (HLAPI).  Unfortunately there were all sorts of awkward problems with this (like needing to derive from NetworkBehaviour, which didn’t play nicely with my generic singleton implementation for some reason).  The whole thing was turning into a massive change that would break the entire game until I completed it.  Not to mention it’s still fairly early days for UNET and it’s changing quite a bit as Unity continues to develop it.

    Besides, ultimately I might be better off using their low level networking API, but that would obviously take even longer to implement.  Or, perhaps using a third party system like Photon Bolt would be a better way to go.  I’d need to spend a lot more time on this to figure out the best thing to do, so I’m leaving it for now.  Instead, I um…disabled those pesky deprecated API warnings, there you go, job done!

    What’s next

    So, it’s generally been a frustrating few weeks, hopefully I can get back to being more productive now!  I’ve been prototyping something for the game, not sure if it’ll work out yet, but I’ll be continuing with that.

    Also, I’m going to work on improving the construction controls, in particular to help new players pick up the game and get started.  Well, that’s the plan anyway!

  • GearBlocks Demo 0.4.6095

    New desert map

    At long last, I have done away with the old procedurally generated terrain.  I decided that it made more sense to have a few decent “hand crafted” maps in the game, rather than an almost infinite number of crappy ones!

    So, now in it’s place there is the new desert map.  This is still a work in progress, I have a lot of details still to add to it, but the main thing for now is that it at least has a flat area to build on without stuff rolling away.  In the full game I plan on adding other maps based in different settings (e.g. forest, grassland, salt flat, snow / ice, etc. haven’t quite decided yet).

    Rendering improvements

    Having upgraded to Unity 5 this allowed me to make the switch over to physically based rendering (PBR).  Besides making things look pretty, PBR serves a practical purpose in that you can now visually distinguish materials (e.g. metal actually looks like metal now).  It also makes it much easier to achieve consistent lighting across the whole scene.

    I’ve also upgraded the time-of-day system, and tweaked the post effects too.

    Saved game format

    The saved game format has changed slightly, so old saved games won’t work in this build.  However, saved constructions from the previous build version (0.4.6034) should still load OK.  If you have saved constructions from versions earlier than that, I’d recommend loading them in build 0.4.6034, then save them back out, they should then load properly into the new build.

  • photo from Tumblr

    First pass of new “Desert proving ground” map for GearBlocks, this (and other maps too eventually) will replace the old procedurally generated maps.

    I’ll be adding more details to this map as I go, but for right now it has a variety of terrain types (sand dunes, rocks, large and small bumps), as well as (most importantly) a large flat area to build on!

  • photo from Tumblr

    Just updated GearBlocks to use PBR (physically based rendering), here’s the before and after.

  • GearBlocks Demo 0.4.6034

    Unity 5 upgrade done (mostly)

    The last remaining bugs caused by the Unity 5 upgrade (at least, those that I’m aware of) have now been fixed.  In the end I decided to postpone migrating away from the deprecated APIs for now as the game still builds ok without doing this (albeit with some warnings), and it’s been so long since the last build - I wanted to get one out as soon as possible!

    New world tool


    There is now a “world tool” in the game (that can be activated by pressing 0), and with this tool active, holding / pressing Q brings up the world tool UI.  In this UI you’ll find the world constructions tab (moved over from the builder tool UI).  You’ll also find a new “settings” tab that allows global settings to be changed during gameplay.  You can change things such as the current time of day, but perhaps more interesting are the new simulation settings.

    These allow you to adjust the trade off between physics simulation accuracy and performance.  For example, if you have a slow computer, you can reduce accuracy to get a better frame rate.  Or, if you have a model that requires higher physics accuracy, you can increase it at the expense of performance.

    Here’s a brief explanation of these settings:-

    Update rate - This slider sets the number of times per second that the physics simulation is updated.  The higher the update rate, the smaller the time step from one update to the next which gives greater accuracy, at a higher performance cost.  The sim time step is particularly important for constructions that have parts with high velocities, especially large angular velocities (i.e. high RPMs).  In these cases, it may be necessary to increase the update rate to prevent instability or “glitching”.

    Constraint accuracy - This slider controls how tightly rotary bearings, linear bearings, and so on are constrained (how little they “sag”).  It also affects how much torque gears can transfer without slipping.  If a construction has parts that exert large forces between moving attachments or gears, this may need to be increased (again, the downside being reduced performance).

    A science experiment

    As (I think) an interesting aside, it turns out that actually two factors affect how accurately constraints are resolved.  Increasing the number of physics solver-steps-per-update increases constraint accuracy, but so does reducing the simulation update time step.  However, I want the player to be able to adjust the sim update rate without also affecting constraint accuracy, so I did an experiment in the game to try and figure out how to keep a consistent level of constraint accuracy while varying the time step.


    I built a construction that put some gears under torque loading (using a lever and a big weight on the end to provide the torque loading).  At various sim update time step settings, I adjusted the number of solver-steps-per-update to just the point where the gears no longer slipped.


    Plotting these results out on a graph showed what looked to be some kind of power relationship.  With a little help from Wolfram Alpha, I found that yes indeed the number of solver steps required was proportional to the time step raised to a power - a power of 2 in fact, handily enough!

    So, now I set the number of solver-steps-per-update equal to the square of the time step multiplied by the constraint accuracy value that the player can adjust, and this gives a nice consistent behaviour.

    Collision behaviour improvements

    You can no longer accidentally deselect or unfreeze constructions under the ground or inside other constructions (this used to generate large impulses as the physics engine tried to resolve the collisions, flinging stuff all over the place).  For the same reason, I have also prevented collisions between frozen constructions and the player or other non-frozen constructions.  This has the added benefit that you can now walk inside frozen constructions to get a different perspective when building them!

    Well, this is a big update for GearBlocks with lots of changes, particularly the Unity 5 upgrade.  There could still be bugs or problems introduced that I haven’t spotted yet, so do please let me know if you find any, thanks!

  • Unity 5 physics issues finally sorted

    At long last, I have resolved all the remaining physics problems I was having with Unity 5!  As I mentioned in my previous blog post, I had solutions that I was working on for most of these issues, but the one thing I wasn’t sure about was how to fix the joint velocity drives.

    Configurable joint drives

    One of the things that changed from PhysX 2.X and 3.X, is the way that joint drives are configured.  They no longer have a mode flag to specify whether they are position or velocity drives.  Instead, if you want a “position drive” you set the drive’s spring value to be non-zero, if you want a “velocity drive” you set its damping to be non-zero (and if you set both to non-zero the drive behaves as a damped spring).

    The question is, what non-zero value to actually use?  Nothing in the Unity or PhysX documentation seems to help much here.  I use both position and velocity drives in the game, and I want them to be constrained only by the maximum force that the drive is set to use (in other words, fully “stiff” as if the spring or damping values were effectively infinite).

    So I tried setting them to float.MaxValue, but this caused some odd behaviour.  Drives configured to be “velocity drives” would not work if the rigidbody’s mass was below some threshold, and those configured as “position drives” would sometimes cause Unity to crash completely without any warning.  In the end, after some experimentation, I simply used a smaller (but still very large) value for the spring / damping settings.  This seems to work alright, although I’m somewhat concerned it could still fail in some unforeseen situations!

    Simulation update rate

    As I mentioned in the last post, swapping joint rigidbody ordering (i.e. owner vs. connected) helped a lot to improve simulation stability at high angular velocities.  Unfortunately it was still not quite enough to get back to Unity 4 / PhysX 2.8 levels of stability.  The simulation update rate also needed to be increased a bit (by reducing Time.fixedDeltaTime), at the expense of performance.  So, as a compromise, I will be exposing a setting in the game to allow the sim update rate to be adjusted.  Advanced users can change it based on the construction that they’re building, and how fast their computer is.

    Last few bugs

    With these issues taken care of, there’s now nothing to prevent the upgrade to Unity 5.  I’m still working on migrating away from some deprecated APIs and fixing a few remaining (non physics related) bugs, once this is done I’ll be able to put out another demo release.

  • Unity 5 physics update (again)

    Over the past few weeks I have been working on resolving the physics issues that are preventing me from upgrading to Unity 5.  For those that don’t know, Unity 4 uses PhysX 2.8, whereas Unity 5 uses PhysX 3.3, the new version being a major re-architecture of the PhysX implementation as I understand it.  The resulting differences in physics behaviour have caused me a fair few problems.

    A while back I outlined these problems, but I’ll run through the remaining ones again here, along with the current state of play for each of them.

    Collision contact tolerance
    The collision contact tolerance is important to set up so that adjacent parts in a construction have enough leeway to slide past each other without jamming up, while also not allowing parts to sink too far into each other.  In order to replicate the same contact behaviour in Unity 5 as in Unity 4, it turns out you have to set the collider’s contactOffset to the same value you had Physics.minPenetrationForPenalty set to in Unity 4, and then also shrink the colliders by this same amount in all directions.  This shrinking was a bit annoying to have to do, as I use the collider dimensions for other stuff, but at least it seems to have done the trick.

    Instability at high angular velocities
    Physics engines, given that they integrate at discrete time intervals (rather than being continuous like IRL physics), often struggle with objects with high velocities, the only way around this really is to update the simulation more often with a smaller time step.  So in order to allow for rapidly spinning parts like gears, axles, etc. in GearBlocks I have to use a small time step (Time.fixedDeltaTime), otherwise things would become unstable and start wobbling all over the place.  However in Unity 5, I had to set it to be even smaller in order to get the same level of stability, unfortunately offsetting much of the physics performance gains over Unity 4!

    Each joint connects two rigidbodies, one being the owner of the joint, the other the connected rigidbody.  One thing I discovered that helps with stability is to set up the owner / connected relationship in a particular order.  The PhysX documentation recommends having the rigidbody with the higher mass of the pair be the owner.  I found that it was even more effective to have low velocity parts (e.g. blocks, motors, etc.) be the owner, and those with high angular velocities (e.g. axles) be the connected.  Setting joints up in this way meant I could get stable behaviour in Unity 5 without having to reduce Time.fixedDeltaTime by quite so much.  Unity 5 / PhysX 3.3 seems super sensitive to this ordering, whereas Unity 4 / PhysX 2.8 doesn’t seem to care.  It’s tricky to set up though because I don’t know ahead of time which parts of a construction are going to be the fast spinning ones (and I can’t change the ordering once the construction is unfrozen and moving without causing other problems which I won’t get into here).  So right now I’m working on something that’ll use an educated guess and hopefully get it right in most cases.

    Unstable collision behaviour
    In Unity 5, for some constructions when contacting flat ground, their collision response with the ground isn’t very stable and they can keep bouncing around for ages after the initial collision.  What’s more, this gets worse the smaller the simulation time step.  Setting up the joint rigidbody ordering as I discussed above seems to reduce this instability though.  Also setting the rigidbody’s maxDepenetrationVelocity to a smallish value helps too.

    Joint drives (used for motors)
    I was finding that the same force numbers for joint drives were giving different results between Unity 4 and 5.  I discovered that in Unity 4 the JointDrive’s maximumForce value should be multiplied by Time.fixedDeltaTime (which is what I was doing), whereas in Unity 5 it should not.  In other words, Unity 4 expects an impulse value, but Unity 5 wants a force value!

    Configurable joint velocity drives
    Once I grasped the differences in the way the settings behave, I was able to get these working, sort of.  I found that they still don’t work if the rigidbody’s mass is below some threshold, and there also seems to be a dependency on Time.fixedDeltaTime.  Not really sure what’s going on here, I need to do some more investigation on this one.

    Getting there, but more to do

    Well, if anyone out there is still in the process of upgrading to Unity 5, I hope my findings might be useful to you!  I’m hopeful I can resolve all this stuff soon, after which I still have to migrate away from some deprecated APIs, and work around a bunch of other bugs and issues I’m having in Unity 5.  Anyway, I can’t wait to put this upgrade to bed so I can get back to actually making the game!