Posts Tagged ‘mecanim’

Guards vs Skeletons

June 4, 2013

Hi folks,

So I’ve done a little more work on my project.  This time I’ve sandboxed the progress in a new scene, with a road and some buildings.  The main aspects of experimentation have been Unity 4.1’s new MecAnim animation system, patrol pathing, and basic AI for recognition, attack, retarget, knockout and respawn.

TL;DR – here is the video:

As you can see the combat behaviour is not totally optimised but the general idea is there.

In terms of working materials, I have used a couple of assets from the asset store (one purchased – the guard and associated mecanim animations, the other free – the skeleton model and animations), and also some AI scripts following a bread trail starting  here.  Working with the AI scripts was quite interesting.  Amongst the key learnings I gathered (or rather, the key bugs), I discovered that quite a few were simply due to the fact that I had transforms in the wrong location.  Making extensive use of Debug.Log statements to check that the flow of the script was working as I expected was very useful and helped guide me to avoid various pitfalls.  I also found that simply defining obvious booleans (eg, Engaging, Attacking, Friendly) was helpful for debugging.

Basically what I wanted to implement was the following – a situation where there are three types of creature: players, guards, and mobs (enemies).  Enemies view players and guards as viable targets, players and guards view enemies as viable targets.  If there are none of the other present, guards (or monsters) will path on a preset sequence of waypoints.  If a hostile rel them passes into their line of sight (I found that checking for ray collision was largely empty unless I raised the ray emanating from the creature a nominal height; this was due to the nature of capsule colliders I am using for creatures), or is sufficiently close (their “noise” > given threshold value) then they move to engage that target.

Once they are adjacent to the target they move to attack it (I found that I needed to reset the transform periodically for creatures when they were attacking, otherwise it bugged out, ie they did not stay fixed in place.  Even when I did this I became confused since it was still bugging out, but then I realised I need to fix the rotation as well.  So prior to attack I calculated the initial position and rotation information and then fed these as temp vars into the attack function).  If the target moves out of range they follow and re-engage.  If the target is reduced to < 0 hp it is destroyed; the associated spawn point for that target is then empty.  The spawn point then detects this and a cooldown timer is initiated.  Once this cooldown timer reaches 0 a new creature is popped at the spawn point and starts to patrol, etc.  As part of the spawn process the list of targets for the creature which struck the knockout blow is refreshed, and a new goal (hostile creature) assigned if there are any in range.  It then proceeds to attack the new hostile creature.

I decided that skeletons should have 50hp and guards 100hp.  They both do a similar amount of damage.  In the video you can see the cycle of destroy-respawn-destroy-respawn, an unending tide of guards and skeletons leaping to rejoin the fray to replace their fallen comrades.

One more thing is worth mentioning.  I also kept track of variables to make sure that the animation playing is appropriate – this is the MecAnim part of the picture.  So the guards and skeletons have state machines for their animations, as well as for their AI behaviour.


I am reasonably satisfied with the outcome, but I know that in theory the implementation could be a lot cleaner.  My code is not totally unreadable but still is, for some scripts, way too long and should be written in a more sensible, concise format.  I’m also certain that in a few places I’ve written out the same functionality more than once; a bit more focus on reusability certainly would not go amiss.  And also redundancy – I’m fairly certain that the code is not as tight as it probably should be, in fact, I know that it isn’t.  This applies more generally to the project at large.  There are many places in my work where I’ve coded the same functionality for different things in different contexts.  Or even functions that have not been used.

So a little work needs to be done at some point on said matters.

In particular, todos that spring foremost to mind with this particular line of work (many of which, such as style, readability, best practice etc. I likely will not implement since this is primarily a “finding my coding feet” ongoing exercise):

  • make it clearer if a creature is in combat (ie, none of this running around in circles spontaneously business) – it could be that artifacts such as running around in circles occur because noise isn’t refreshed immediately for the goal creature when the original target is destroyed.  This could be fairly easily redressed.  Or maybe I might like to simply have a fixed (small) radius wherein if the goal is within that circle the creature automatically moves to attack (this is currently not the case, but it should be, and that is what noise/”sound” detection (generalisation of said idea) was supposed to do)
  • possibly aim to fix creatures in place during combat – try to make things more static
  • morale stat for creatures – chance to run away if allies nearby down / no support (possibly hard) or hp low; then move randomly away from attacker, or seek “wall” tagged object to attempt to throw off attacker?
  • knockout animation & possible option (if player dealt k.o.) for ability to loot the creature; then despawn timer prior to respawn
  • refactor the code to make some of the classes less lengthy and so that they have a more logical structure
  • subclass creature.cs (my main AI script) as part of a SFS_creature.cs script so that it interacts well with smartfoxserver
  • NPC_targeting.cs (my main AI targeting / listing script) – make this dependent more on “Broadcast messages”, possibly local messages.  There is a messaging system I am currently using for health bars – this however is more general and can be extended.  If the world becomes quite large and hence contains 100s of monsters, guards, players etc I do not want every single monster / guard / player to have a list of length 400 encoding and tracking the position of everything else in the world – that would be untenable.  But that is precisely how the program works currently.  Evidently this will have to be fixed, so that only enemies / guards in noise / detection / aggro radius are detected.  Or “targeting radius” which is larger than aggro radius.
  • Incorporate the idea of “threat” levels depending on which creature is damaging which – ie first calculated purely as a function of total damage dealt, then maybe factoring in threat generation abilities (eg taunt – sets to top threat) or threat reduction abilities (feint), and threat reset effects (moving beyond targeting radius – as per point above).  Evidently want the creature with highest threat to be the creature targeted.

The next part of the project will focus on hooking up a mysql database with the smartfoxserver software I am using as described here.  Basically I’d like to aim at storing 8 fields: username, password, spawn location (x,y,z) and last seen location (x,y,z).  Essentially I would like last location to be updated every time the player logs out, and then persisted in the database, so that when they log back in (if it is not a first time logon), they appear at that location.

If it is a first time logon they appear at the default spawn location, and last location is null until populated.

The architecture of the goal application will essentially be

client unity application <-> server SFS2X application <-> mysql database

with <-> denoting two way communication, the client application written in C#, the server application written in Java, as is currently the case; the new component will be the database.  Naturally a database can consist of more than one table, and more than 8 fields.  In a full blown, sophisticated application, there is no reason that all data about the players should be able to be stored in an appropriate database schema.  So certainly there is considerable room for extending this aspect of my learning, once I’ve managed to get this proof-of-principle up and running.

Consequent to this I might look at readapting this patrol example for SFS2X-deployed unity games, or something completely different.

Ideas as to things I should probably look into doing next

May 27, 2013

Hi folks,

In addition to some of the things mentioned in the last post, I’ve had a bit of a further play, and have identified to a better degree as to what I would like to try to implement next.

Namely, I have been having a look into MecAnim to a greater or lesser extent – in particular finding this tutorial quite useful.  I’ve since accumulated a bit of a library of basic animations, and a few models, old and new.  In addition to this, I’ve been looking into patrol pathing for the creatures in question, sandboxing this work within a new scene.

Essentially what I would like to achieve is to have a group of friendlies – guards, on a set patrol path, and a group of enemies – skeletons, also on a set patrol path (inspired by this resource). When the two come within sight radius of each other, I want them to close for melee combat.  Upon attack, I would like the other creature to sense this and also join combat.  Creatures will have to face in the correct direction and be within a certain range for combat to be permissible.  In addition, I would like each creature to have a set number of hit points.  When this reaches zero, I would like an appropriate animation to play – then a moderate delay prior to destroying the prefab.  Then I would like a replacement enemy / guard to spawn and start walking along the original patrol path until it sees an enemy / guard, then charges to initiate combat, etc.

In terms of animations, I would like a walking animation to play while the creatures are walking, maybe a pause and idle animation at each waypoint, or certain specific waypoints, and if an enemy comes into sight radius / arc I would like the model to charge until within melee distance – at which point it is to stop and play an attack animation.  For a more convincing experience, I might also like to build in a “morale” stat, which determines at what health % the enemy / guard is likely to break and run in a random direction, at reduced speed.

I would also like the player to be able to join combat on one side or the other, most likely in favour of the guards.

For a bonus feature, I would like to have a button on the player HUD that allowed the following effect to occur – random spawning of large boulders falling from the sky, at say 5 or 6 (or maybe 10?) fixed and predetermined spawn points for the purpose.  ie so that at every predetermined time interval (allowing for delta time so that the implementation is hardware agnostic), a random number (say 1 to 3) spawn points are randomly selected.  Prior to impact I would like there to be an obvious red glowing marker at the location that the boulder will fall.  Then I would like the boulder to spawn and fall at some predetermined speed, and autocrush any avatars beneath, forcing respawn.  Subsequent to impact I would like the boulder to decay after some period of time, maybe with a lifetime of 1 minute  (In the intervening time I would like it to be treated as a wall for pathing purposes, as according to the particular AI script I will be using).

I would then be interested in implementing a dive and roll animation into the player controls, and possibly introduce a stat “reactions”/”reflex” to guards / skeletons, which make it more likely that they will detect imminent impact and also dive out of the way, even if they are in combat.  I would also like to be able to switch this effect off from the player HUD at will.

Later, time and resources permitting, ideally I would like to introduce missile combat animations (bow and arrow, and/or crossbow, sling, etc), and magic combat animations, to allow for guard / skeleton variants that can engage in combat at range.

So that’s my animation plans.  For the time being, as mentioned above, I intend to sandbox this activity, since converting the work to something that is synchronised in a SmartFoxServer might make things harder to build initially; I can do the legwork for that later.

The second thing I am interested in doing, and will probably take much longer to figure out, is to determine how to integrate a MySQL database with a SmartFoxServer application.  The ultimate goal of this will be to implement an architecture wherein I can store player specific login names, passwords (so, for instance if this was a licensed game, they would need to transact, or at least register to obtain a name and password), together with a table containing the set of all that player’s characters and their names, together with a table that, for each character name (uniquely specified for the server (for chat considerations)), contains the information as to health, stats, and inventory.  Inventory would be a string that contained a list of words, eg, potion, wand, leather armour, broadsword, that would presumably be read by the SFS extension jar file and allow the server to transmit to the client the data that relates to the items they have.  That sort of idea, anyhow – so that the data, related to persistence of character state, for the collection of characters each player has, is stored on the server.

So that’s the goal.  I do not expect implementation to be easy, particularly since documentation seems relatively scarce regarding such.  However, this post looks like a good place to start on said matter.  In particular, it is indicated how one might set up a custom SmartFoxServer via the RightScale platform if one wanted to deploy the server in the cloud, say on Amazon EC2, via the 12th point of the recipe (one can directly modify files while booting up/setting up a virtual machine on RightScale).