LAN Battle Game

I made a small battle game, you control a square and use awkward keys to jump around, kill other players by jumping on top of them.

Z: Move left
X: Move right
Z+X: Jump

R: Change costume
S: Respawn

Sword: Kill people by walking into them
Shield: Block sword attacks

Multiplayer LAN battle game
Play in browser

Players were supposed to be blobs which can expand (by pressing Z+X), causing them to bounce up, but that looked lame. Players could also wallrun, but that made controls too confusing.

RTS4 Data File Structure

There haven’t been any gameplay changes recently, instead I’ve been working on adding features for modding. The current proto data format automatically supports a lot of scenarios, but many common concepts can be tedious to write. The latest build includes some of those changes (and a lot of bugs).
RTS4 Release 9
Webplayer (Unity)

I’m working towards supporting advanced scripts like this RPG-style script:

Player.default {
  Level = 1;
  Experience = 0;
  NextLevelXP = $Level * 200;
  Health = 200 + $Level * 20;
  RequireComponent<AttackMelee> {
    Attack = 20 + $Level * 2;
    OnKill = (other) {
      Experience += other.$XPGain;
    };
  };
  Event(Experience >= NextLevelXP) {
    Level += 1;
  };
}
Grunt.default {
  XPGain = 1
}

Several fields (NextLevelXP, Health, Attack) are augmented by other fields. By default, these fields only include the augmentations that appear prior, adding a $ causes all augmentations to be used. Using this feature does introduce the possibility of cross-dependent fields which would crash the game; I’ll need to add some protections for that later (probably just not run those augmentations recursively). An example of something that would break it is:

Health += $BonusHealth
BonusHealth = Health * 0.5

The OnKill event handles giving experience when they kill a grunt. Any augmentations that appear in these scripts are somewhat special; a single augmentation is allocated at compile time, which starts off as the identity value; whenever the script is run, the augmentation value is changed by whatever the script says. This has the benefit of allowing any other augmentations later in the file to still be applied correctly (ie. if Experience *= 2 appears in a later technology, the experience will correctly be doubled until that tech is removed).

Finally, the script creates a level up event to be run when the players experience passes the required amount. Because of the $ in earlier dependent fields, changing the level later in the file still correctly affects Health/Attack/NextLevelXP.

Currently fields referencing other fields, and simple scripts are supported. Its also possible to define “APIs” (RequireComponent and RequireTechnology are now external APIs) to provide more functionality, without bloating the code.

RTS4 UI Art

I spent the day fixing up the UI and drawing some nice textures so its a bit nicer to look at. They are still placeholder.
RTS4 UI Art

I also played a bit of Age of Mythology: Extended Edition and got frustrated at the loop icon being difficult to see (or just not showing at all..) so I made a really obvious visual effect for when autoqueue is active. I’m quite happy with how it turned out, and its fairly efficient (the mesh resizes to fit the arrows snugly as they bounce at the start). I would love to hear what you think of it!

RTS4 Progress

There were a few glaring features missing, but the last build was mostly complete functionally. I’ve since been working on getting the game to feel much more polished.

Prototypes

The prototype system used for unit configurations was changed to be far more flexible and will work more like CSS, where “technologies” (classes in CSS) have various selectors which determine which entities they are active for. Fields are overwritten in the same way, but a single units prototype can be spread throughout the file; the end result is that it is now easy to add upgrades that can have a significant effect on the game.
Unity RTS4 SignalFires upgrade example

Selection/Placement

I never paid much attention to selection previously, but entities can now be box-selected by boxing any part of them (instead of just their origin). The units centre is restricted to the current box selection, then that restricted point is tested against the units collider to determine if the unit should be boxed or not. Buildings also attempt to move to a valid nearby place when attempting to place them on top of another building (with standard 2D un-intersect style physics)

Projectiles

A game will obviously have a lot of projectiles (arrows, priest attack, etc.), which all act very simply. Theres now a special subsystem dedicated to handling projectiles in a much more efficient way than creating a new entity for each projectile. They are rendered and (soon) animated with the same prototype configuration as normal entities.

MiniMap

This one is a much more substantial feature addition. The game now has a minimap which rotates with the camera and shows/allows movements of the camera frustum. I may look in to dirty sectioning for it later, but the draw overhead is so minor that it probably doenst matter that its O(n).
Unity RTS4 MiniMap Screenshot

Optimisation

The game now tracks a separate list of entities which need to be updated each frame, which is only units tasked with a command. It is possible to reduce this to only units which have a move command, but the current method is likely fast enough. The game also has an EntityMap, which tracks nearby groups of entities (white boxes in the image below). Entities will delay repathing when given a new target until required. Loading is still too slow for my liking; it takes 80ms to parse the prototypes and 550ms to instantiate entities in the current demo map, but optimisations come later!
EDIT: Oops.. I still had some testing code in there; instantiating entities takes 50ms now.
Unity RTS4 EntityMap Debug View

Multiplayer

Was working well previously, but some of the newer optimisation and validation changes have probably broken things. Dont expect this to work terribly well until nearer to release.

Webplayer

Back to RTS4

The previous tutorial series covers most of the basics for an RTS. I probably wont be doing any others for a while as I’d now like to concentrate on RTS4. There has been some quite significant progress made to the project; with the cleaner design from the UnityRTS tutorial series, and the separation of simulation from visuals, the project is much easier to work with now.

Separation of logic

In the UnityRTS projects, although updating happens at a fixed time interval, the coupling of the simulation and visuals makes it difficult to have simulations running in the background and ties the game more closely to the Unity engine (which with Unreal looking so nice, I want to avoid). These two functions are now separate, and each client now runs two simulations concurrently; one for the last known server state, and one for the clients visuals. Each network message is first run on the server, if it is prior to the clients visuals simulation time, the client sim is synced to the servers sim, and then rolled forward to the correct client time. This gives clients no lag while still minimising network bandwidth. As the visuals are separate to these simulations, they can smoothly interpolate whenever the client simulates incorrectly.

Prototypes

The decoupling of the simulation from the Unity visuals means that entities can no longer be described by components on a prefab. To replace and extend this system, each entity now has a prototype object, which calculates any stateless properties (its max health, build time, etc.). Getting a field is not as simple as looking it up by name; Prototypes have a list of technologies which can be enabled or disabled which augment fields, enable / disable components, and even enable / disable other technologies (both for just this entity, or for all entities owned by the player).

These toggleable technologies mean that entities can very simply support buffs and debuffs, by for example enabling a SlowPoison technology. The system also handles armoury upgrades by enabling the HardenedShields player-wide. And it can even be used to handle tech unlocks, for example by enabling age2 player-wide, which can in turn augment the villagers Builds list to include Barracks and Farms.

I dont fully understand the effects system in AoM, but this seems more extensible and quite happy at how many common RTS concepts it can support cleanly. None of my previous attempts included anything like this, so its great to finally understand it.

Unity RTS4 Prototypes example code for Villager

Multiplayer

With the changes above, multiplayer is now functional. I’m using the RPC support in Unity to send messages (after serialising them to byte arrays) which conveniently handles lobbies and NAT punchthrough for me.

 

The current version can be played here (with multiplayer disabled at the moment). I also added in the older models instead of boxes.
RTS4_7.4
Webplayer

Unity RTS – Part 6 – GUI

Although promised many times, Unity still does not have a decent UI layout engine. The process can be simplified with NGUI from the asset store, but its still tedious. For UnityRTS I opted to use a system similar to the built in GUILayout, but tried to make it much simpler to use for common use cases. It works off of a loose hierarchy of elements, with three main functions.

Most of the time, child elements will borrow a slice from their parents; removing that space from the parent and giving it to the child. This is done through WidthSlice() and HeightSlice(). Another common function is tables and grids, created through the Grid() function. After specifying the number of rows and columns, calling Cell() on a grid returns the next cell (iterating horizontally then vertically). The final function is a flow layout, though not integrated as nicely as it could be. This scales down items uniformly to fit the specified number of items in the allocated space; much like grid, but the item dimensions and count are provided, and item aspect ratios are preserved.

The UI in UnityRTS is modelled off of Age of Mythology. Two height slices cut the top and bottom bars, and various other functions allocate required space. Information is pulled from the game scene as required. Also made some pretty box art for things 😀

unityrtsui
Webplayer | Download Project

Unity RTS – Part 4 – Vision blocking

Its been a while! This time I’ve made a lot of tweaks to the Line of Sight code so that items can correctly and efficiently occlude unit vision and implemented pathfinding using flowfields for smoother unit motion. Both items took quite a bit longer than I had anticipated and are probably still quite slow, but I’m happy with how they are looking. This post will talk about the vision blockers; I’ll leave pathfinding for the next.

Some code existed in the previous build for entities to write their blocking height to a grid covering the game world. This grid tracks the highest unit on each cell and blocks sight for all shorter units. The RevealLOS method has been rewritten to now more accurately read this data and project “shadows” outward to hide areas of terrain. The algorithm has two distinct phases.

Pass 1 – Occlusion angles

The first pass iterates through all tiles within the reveal radius, ordered by their occurrence when sweeping clockwise. Think of this as a radar, which pings for each cell as the detector passes them. This ordering is important to keep the input clean and reduce the amount of work needed later.

Each cells height is compared against the current units height, if the cell is too high, it is added to an ordered list of blocking cells (ordered the same as the iteration, clockwise around the unit). The distance and angles for where the blocked vision starts and stops are also cached. A small optimisation pass is done on this data to remove cells that are eclipsed by other cells nearer to the unit center; these are redundant, since any terrain they occlude will already be occluded by the nearer cells.

Pass 2 – Terrain reveal

The next pass iterates over all tiles within the reveal radius, determines their distance and start/end angles, and looks through the previous list of occlusion cells to determine how much of the tile is occluded. As the occlusion items are ordered, iterating this list forward and shrinking the visible arc is sufficient to correctly calculate occlusion for the left-most angle. This is then repeated in reverse for the right side.

The result of this calculation is four angles; the tiles initial start and end angles relative to the unit, and the unoccluded start and end angles. The visibility of each tile is simply the unoccluded arc size divided by the total tile arc size.

Optimisations

Trigonometry functions are expensive to execute, so “angles” here are approximations. A full circle in this system is 8 degrees, and calculating the angle of a vector is simply determining what quadrant it is in, and then dividing the coordinates.

It is impossible for the arc of a nearer cell to be smaller than a farther cell it is projecting onto. If this were not the case, it could be possible for small arcs to lie entirely within a tiles arc, and be ignored by the system.

losoccluded

View online or Download Project (note: has some unfinished UI code in there too)

Unity RTS – Part 3 – Resource Gathering

Most of the interactions between entities in an RTS revolve around trading resources between the player, environment, and enemy. If we consider unit hitpoints to be a resource, which causes death when depleted (much like trees when exhausting wood or mines when exhausting gold), implementing HP in the same system as other resources looks like a reasonable thing to do. However, in reality, this turns out to greatly complicate the content pipeline.

There are a number of subtle differences between the default configuration for health, and for other resources an RTS might have. By default:

  • When an entity damages another entity, it should not gain the damaged health for itself
  • Health should not be transferrable between entities
  • There is no global player health (ie. player stockpile for Food/Wood/Gold)
  • Armour types dont make sense for other resources

Many of these should be optionally possible, and there are many other behaviours that are shared between the two (animation timing, buffs, range, depletion events). I am not sure of the best approach when dealing with these two similar systems; for this project I am choosing to use polymorphism to expose similar capabilities with different defaults. A base class InteractionAction will provide logic for interacting with a target entity (offering range, action interval, and sub-action logic), with two specialisations for AttackAction and GatherAction, which provide inspector variables and the missing logic.

Eventually I would like to support something like an entity that generates 1 gold for every 2 hitpoints that it deals to an enemy. This will need to be implemented with a 3rd specialisation, CustomAction, which allows arbitrary resource exchanges on various events (perhaps also a boomerang that damages whatever it hits, and heals when it returns?)

Most of the logic for this system takes place in InteractionAction. This class handles moving toward a target, and then repeating an interaction at a set interval (ie. move toward a tree, then “chop” to gather some wood every second). The class internally holds a SubRequest, which is used for the current “stage” (this would first be targeting the tree, but once enough wood is collected, it would then target a resource drop site). It is up to the subclass to override BeginStage to determine the best target for the action (ie. if the unit is already holding its full capacity, look for a drop site, if not, try to mine resources) and call EndStage where appropriate (ie. after the resources were dropped, or after capacity was reached).

The component does not yet support projectile interactions, a nice way to implement them would be to create a new InteractionProjectile component and hold a reference to it in InteractionAction; creating new instances on each NotifyInterval() call, and having it call back to InteractionAction on specific events (hitting enemy, returning to source unit).

UnityRTSP3
As usual, heres a webbuild, and the project files.
The light-blue boxes are resources, dark-blue is a resource drop point, and the other sphere is an enemy that can be attacked.

Things are getting hard to debug without a UI, so I may skip pathfinding and do UI next instead.

Unity RTS – Part 1 – Framework

I’m going to start a series on building the major components of an RTS in Unity, starting with how to develop a typical framework. RTS games remain one of the most complex and difficult game types to create, dont expect to have anything fancy working for quite a long time.

Networking Considerations

Most developers looking to build an RTS will be looking to include a multiplayer component. I wont go into a lot of detail, but supporting multiplayer in a game with hundreds of active units constantly doing things in the world is quite difficult; 1500 Archers on a 28.8: Network Programming in Age of Empires and Beyond does a much better job of explaining the typical approach used (though some other approaches also exist). A well designed RTS should have a layer which all input “Commands” pass before interacting with the world; this layer synchronises actions through to the various clients to ensure the world simulates correctly for each client.

Components

An RTS framework will likely involve the following components (and more):

  • Entity: Represents the base data that each object within the scene contains (Name, Player, Health)
  • Action: Contains logic for an action that an entity can perform
    • MoveAction: Take a target location and walk the best path to reach that location
    • BuildAction: Invoke MoveAction; when in range, begin construction on a Buildable component
    • GatherAction: Invoke MoveAction; when in range, gather resources from a ResourceSite component
    • AttackAction: Invoke MoveAction; when in range, reduce the target Entitys Health
  • Components: Optional items that augment the way an entity acts
    • Sight: Cause this object to reveal the surrounding area
    • Buildable: Accept build actions from other entities; when complete, swap for another entity
    • ResourceSite: Hold an amount of resource that can be gathered
  • Pathfinder: Store terrain information required for pathfinding and provide pathfind query results
  • Player: Store information about a player (Name, Colour, Alliances)
  • Command: A target and action to be applied to a set of entities
  • SceneManager: Handle executing commands in the correct order and at the correct time, and querying for entities
  • LOSManager: Hide objects that are out of sight of the player
  • SelectionManager: Store and allow interactions of the currently selected entities
  • CameraManager: Handle camera movements
  • BuildManager: Allows the player to interactively place buildings when a building type is selected
  • InputManager: Receive mouse and keyboard inputs and send them to the appropriate manager

To ensure the game simulates correctly on all clients, no gameplay-altering information should ever leak into the entities or their actions/components except through generating Commands. Unfortunately, Unity makes this constraint very difficult to enforce; at any point a script can change the state of an entity or an action can query the Input class and cause a client desync. It is entirely up to the programmer to make sure that never happens.

Implementation

UnityRTSP1
I’ve created a very basic framework, you can view it online here, or download the project file here:
http://weesals.com/Releases/Unity/UnityRTS/Part1/UnityRTS.zip
Its very simple, dont expect much.

This project contains a working Action system, though has only a partially implemented Move action. Entities can be selected by clicking or box-selecting them, they can then be ordered to move by right-clicking the terrain or another entity. Right-clicking another entity will cause the target position to continually update, and cause the entities to follow.

New actions can be implemented in a similar way, and then dragged onto the object via the inspector. An AttackAction may subclass the MoveAction and only run base.Step() when the object is too far away to attack. Once the objects are in range, it can then begin the attack logic. The action with the highest score for a given request is used, thus an attack action returning a score of 2 when targeted at an enemy entity would be used instead of the MoveAction returning a score of 1.