For my Game Design program’s Capstone year I have taken on the primary role, “Programmer”, for Team Voyager, and as such will be chronicling the process of creating a versatile player controller for use within the Unity game engine. Having created multiple first-person controllers in the past, and being unable to properly remove the “Unity” controller feel, I have decided to base this player controller of off the Kinematic Character Controller available on the Unity Asset Store, provided by Philippe St-Amand.
The first step of the process was to determine what the team, as a whole, desired for the player controller, e.g. what movement should feel like, if abilities are present and how they should feel, as well as taking into consideration the 8 month timeline for the project’s scope. After getting individual briefs from the team, I was left with the following information as to what our intended “Diverse Movement” meant to each team member.
Blair: Unique movement means, on top of what you expect in a generic FPS (sprint, left, right, jump, crouch) I think it means having permutations of those (double jump, directional dash) something to do with variable physics, climbing is also interesting, grab ledges, coyote time. Nothing crazy, just straying from the generic.
Nick: good feeling movement, think less Call of Duty: Black Ops and more Destiny, it’s in tune with the world, if I look at something and want to go there, I can do a jumping puzzle or there are a variety of ways to get there, sliding is super important as a fluid mechanic.
Becca: Apex legends sliding is a great movement tool, can continue slides downhill if wanted, as well as chain-able into jumps and back into slides
Elijah: Lot of room for verticality, depends on what our medium will be, since we are non traditional implies tool usage, are we using jetpack or traversal tools? thinking about economies for such movement and how it can be applied, we can mess with gravity as we want, and how we will utilize movement abilities, fast or slow matters but zooming super fast AoT style compared to quake movement doesn’t particularly matter. Meso or Micro leaning will be determined by the kind of movement / controller we have for the player
Marcus: I think of deadlock, unique movement system, jumps are variable with other movements, wall bouncing, reduced gravity and increase air mobility.
Brandon: Unique movement to me means the presence of a skill ceiling to movement, in other words the ability to intuitively chain movement as needed or wanted. for example destiny allows for dashing to increase movement speed for a small duration after the actual dash (velocity slowly resets back to the normal run speed), which can be chained with a jump or slide as well as other movement related class abilities, allowing an experienced player to move faster/more precisely. Alongside that, a camera that presents the player with feedback on their movement (leaning cam when accelerating really fast, reference bungie FPS GDC)
To start, I imported the package to a new Unity 6.3 LTS project, utilizing the Universal Render Pipeline. Next, utilizing the walkthrough guide provided by the asset package, as well as various online implementations of said package, I began by structuring out the Player Controller.
For my Game Design program’s Capstone year I have taken on the primary role, “Programmer”, for Team Voyager, and as such will be chronicling the process of creating an management system for subtitles within our game.
To begin, I wrote out some of the requirements that the system would need. Specifically, I wanted to create a system that would require little to no programmer on the behalf of the user. Alongside this, I worked with our Accessibility Designer to ensure that we are following well-thought out guidelines for accessibility customization. The key requirements for this manager are as follows:
Custom editor window (interface for the narrative designers)
Dropdown list for selecting the character’s name during subtitle creation
Allow the designer to preview what a given subtitle would look like within the Unity editor
Automatic formatting of the given written text
Automatic splitting of the written text to separate subtitles
Adjustable Letterbox options
To begin, I wanted to create a custom editor tool, as I have recently learned about extending scripts from the Editor class, allowing for custom inspector windows. Following this, I came across the extensions for the EditorWindow class, which allows us to create full window tools.
Extending from the EditorWindow script allows for a few implemented functions to override, such as: GetWindow<>() and OnGUI():
SubtitleWindow.cs
publicclassSubtitleWindow : EditorWindow{ // Create a custom toolbar menu // When said menu entry is clicked, return // Our custom window, typeof SubtitleWindow [MenuItem("Voyager/Subtitle Editor)] public static voidShowWindow() {GetWindow<SubtitleWindow>(title: "Subtitle Editor"); } // Allows us to draw custom GUI elements within our new window private voidOnGUI() {}}
After creating a small thumbnail of how I pictured the custom window would look, I began to implement the custom GUI elements as such:
SubtitleWindow.cs
privatestring newSubtitleText =string.Empty;privateCharacterTag newCharacterTag;voidOnGUI(){ // Creates a label at the top of the interior panel GUILayout.Label("Subtitle Editor", EditorStyles.boldLabel); // Creates a text field with a label EditorGUILayout.TextField("New Subtitle Text", newSubtitleText); // Creates a drop down selection menu for an enum attribute EditorGUILayout.EnumPopup("Character Tag", newCharacterTag); // Creates a button and ties a function call to its delegateif (GUILayout.Button("Create new Subtitle")) {HandleSubtitleCreation(newSubtitleText, newCharacterTag); } // Update the GUI if there are any changes to the fieldsif (GUI.changed) {Repaint(); }}
The resulting window, although underwhelming and currently not very useful, looks as such:
Following this, we have a few problems to address. First, we need to increase the height of the text field, as well as make the text we enter wrap around, as it currently just displays as one long line. To solve this, I created a new GUIStyle(), and set the word wrap bool to true. We then feed this GUIStyle into the text field’s creation code, as well as setting the fields MinHeight() to 40.
The next aspect I wished to add to the window is a property field for displaying the existing subtitles. Now this is usually a relatively easy task when extending a script from the Editor class, however, since I am inheriting from the EditorWindow, we are not given the useful “serializedObject” variable to add SerializedProperties to. To solve this, we have to manually implement it. The resulting code looks as such:
SubtitleWindow.cs
// Since this is an editor window, we don't get the fancy editor "serializedObject" call// so we build it ourselves, automatically updates when the values are changedvoidHandleSerializedSubtitles(){ // Set subtitle target as object field with type subtitlemanager // return if it doesnt exist _subtitleManagerTarget = (SubtitleManager)EditorGUILayout.ObjectField("Subtitle Manager:", _subtitleManagerTarget, typeof(SubtitleManager), true); // Find our subtitle manager script within the current scene _subtitleManagerTarget =FindFirstObjectByType<SubtitleManager>(); // If the subtitle manager script is not in the scene, breakif (_subtitleManagerTarget ==null) return; // If the serialized object for the subtitle manager is not our current subtitle manager // Set our subtitle manager target to a new serialized object in ref to our manager // Set the property field to the _existingSubtitles list within our manager scriptif (_serializedSubtitleMTarget ==null|| _serializedSubtitleMTarget.targetObject != _subtitleManagerTarget) { _serializedSubtitleMTarget =newSerializedObject(_subtitleManagerTarget); _serializedSubtitleProperty = _serializedSubtitleMTarget.FindProperty("_existingSubtitles"); } // Update the serialized target reference _serializedSubtitleMTarget.Update(); // Create the property field for our existing subtitles // Ensuring that the IncludeChildren param is true EditorGUILayout.PropertyField(_serializedSubtitleProperty, true); // Applying our modified properties should they change _serializedSubtitleMTarget.ApplyModifiedProperties();}
Now, we can add a new subtitle with some text, select a character tag, and hit Create New Subtitle. Using my Subtitle struct, which takes a string and an enum value for the character tag, we create a new subtitle and append it to the _existingSubtitles list (List<Subtitle>) within subtitle manager script. The window now looks as such:
Alongside this, we have the ability to quickly remove individual subtitles, as well as reorder them within the property field. This is useful, as we can now create a prefab with a trigger attached, or directly call from the subtitle manager script to pull a given index and automatically retrieve the data for each subtitle, and process them in the background to split up longer dialogue portions into individual “slides”.
Saving and Loading Subtitles
Now the next step was to figure out a way to save and load these subtitles. I figured the easiest way would be through JSON. Thinking ahead to the secondary programmers tasks relating to options menus, I figured I would implement a system that would allow us to save generic lists of data. Unfortunately, the included jsonutility does not allow for saving of certain datatypes, such as List<>, by default.
For my first attempt to solve this issue, I tried to loop through each of the indices of a given list, and save them out individually via the jsonutility.ToJson() function. This resulted in as many files as there were indices within said list, which was not preferable. I then attempted to concatenate the indices with a divider such as “|”, then read them back, however, the jsonutility.FromJson() function expects only one root item, and I would have to workaround this.
Instead of continuing down this route, I decided to create a generic wrapper for any given list, and have said wrapper hold onto the values we wish to keep. This allows me to create alternative wrappers to hold multiple different lists of data, and easily read and write them utilizing the jsonutility class. This is particularly important for the secondary programmer, as we can save and load different option menu values with individual wrapper properties. I have omitted the single object save functions, as the majority of these cases will be handles by the jsonutility natively.
SaveSystem.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingUnityEngine;// Folder name enumpublicenumJsonSavePath{ Subtitles, Options};// Wrapper for list objects, generic so we can use it for anything// Must be serializable[Serializable]publicclassSaveWrapper<T>{ // List of our given types of objectspublicList<T> objectsToSave;publicSaveWrapper(List<T> objects) {this.objectsToSave = objects; }}publicstaticclassSaveSystem{ // Saves JSON list data to a given folder name and file namepublicstaticvoidSave<T>(List<T> objectsToSave, JsonSavePathsavePathType, stringfileName) { // Creates wrapper for saved objects // We use this as if we were to individually loop through all obj in the given list, // JSON cannot read it back as the syntax is wrongSaveWrapper<T> wrapper =newSaveWrapper<T>(objectsToSave); // Save as JSON stringstring jsonString = JsonUtility.ToJson(wrapper, true); // Write string to given file path File.WriteAllText(GetSavePathToFile(savePathType, fileName), jsonString); } // Loads JSON list data from a given folder name and file namepublicstaticList<T> Load<T>(JsonSavePathsavePathType, stringfileName) {string path =GetSavePathToFile(savePathType, fileName);if (!File.Exists(path)) { Debug.LogAssertion($"Save System did not find a file at: {path}");returnnewList<T>(); } // Read json data at pathstring jsonString = File.ReadAllText(path); // Create wrapper with json dataSaveWrapper<T> wrapper = JsonUtility.FromJson<SaveWrapper<T>>(jsonString); // Return wrappers saved objects as a listreturn wrapper.objectsToSave; } // Returns the save path from a given type and a filenameprivatestaticstringGetSavePathToFile(JsonSavePathsavePathType, stringfileName) { // Start in the Json folder cause all json data should be located therestring jsonPath = Path.Combine(Application.dataPath, "Json");string savePath =string.Empty; // Add cases here for new save types, this designates the folder name under Json in Assets folder // E.g. To add control options, switch (savePathType) {caseJsonSavePath.Subtitles: savePath ="Subtitles";break;caseJsonSavePath.Options: savePath ="Options";break; } // Create new path with given typestring newPath = Path.Combine(jsonPath, savePath); // Ensure folder exists Directory.CreateDirectory(newPath); // return filepathreturn Path.Combine(newPath, $"{fileName}.json"); }}
Now to utilize this save system within the subtitle manager, we can create some simple function calls, and attach them to our custom editor window:
SubtitleManager.cs
// Appends a given subtitle to the list of existing subtitlesprivatevoidAddExistingSubtitle(SubtitlenewSubtitle){ _existingSubtitles.Add(newSubtitle);}// Load subtitles from filepublicvoidLoadExistingSubtitlesFromFile(){ // Clear existing subtitle list _existingSubtitles.Clear(); // Get subtitles from subtitles filevar subtitles = SaveSystem.Load<Subtitle>(JsonSavePath.Subtitles, "TestSubtitles"); // Append each subtitle from file to the current existing subtitle listforeach (var subtitle in subtitles)AddExistingSubtitle(subtitle);}// Save subtitles to filepublicvoidSaveCurrentSubtitlesToFile(){ SaveSystem.Save(_existingSubtitles, JsonSavePath.Options, "TestOptions");}
Now our finalized subtitle editor looks as such:
Final Notes:
Personally, I had a very entertaining time devising this system, as well as learning about extending the functionality of the Unity Editor. Custom tools such as these allow us to create tools for designers, which requires no programming in order to implement. There are multiple ways of handling the creation of tools such as these, and I look forward to continuing my understanding of custom tool creation.
For my Game Design program’s Capstone year I have taken on the secondary role, “Rigging & Animation”, for Team Voyager, and as such will be chronicling the process of creating an automated rig for both arms and legs.
The purpose of creating an automated rig is to cut-down on the iteration process for creating our First-Person view model, taking into consideration that I am the only person working within Maya for the scope of this project. Alongside this, I anticipate the Character Artist iterating over different designs for the finalized arm and leg meshes.
The Setup
As I required a placeholder mesh to preform these tasks on, I sourced a character from Sketchfab | Credit to “WisherZard” | and removed the portions of the mesh that were irrelevant to this project. Alongside this, I patched the top of the waist as one of our stretch goals for the project is to include lower-body animations.
The Arms | Manual Process
As the process for rigging the arms and legs are incredibly similar in many aspects, I will only cover the arms from this point on for brevity.
To start, I began by rigging a pair of arms by hand. The initial step was to place joints within the mesh, whilst taking care to ensure that any joints that would utilize an IK Handle are entirely planar. After creating the spine joints, I created the left arm and mirrored them over using the Duplicate Joints tool and duplicated them via behavior, allowing for rotation to be mirrored across the limbs.
The next step was to duplicate the shoulder->elbow->wrist joint chain twice, and rename the duplicates to differentiate between a FK chain and an IK chain. The purpose of this is to allow us to toggle IK/FK utilizing the node editor and a custom IKFK attribute on the controls.
Following this, we create circular NURBS curves to act as the FK controllers and create empty parent groups for each to hold transform information. This ensures that the controllers themselves have no translation or rotation history. Then, we parent constrain the respective FK joints to their controllers. An example of the hierarchy at this point looks as such:
Now we create two IK controllers, following a similar process as the FK controllers; one for the wrist, and one for the elbow’s pole vector control. (I will touch on the placement of the pole vector controller in the automation section). Following this, we create an IK-Handle between the ik_shoulder and ik_wrist joints, and parent + orient constrain the IK-Handle to the wrist controller. Next we pole vector constrain the IK pole vector control and the IK-Handle. On the IK wrist control, we add a custom bool attribute titled ‘IKFK’, with a default value of ‘False’, as well as ensuring that the attribute is keyable. Following the creation of our custom attribute, we create a duplication of said attribute across all of our controllers, with the wrist designated as the proxy. Using python, the attribute copy looks as such:
Python
defIKFKattrCopy(source, ctrls, attrName="IKFK", isSingle=False):# add ikfk attr from given controller to selected controllers mainCtrl = sourceifnot isSingle:for ctrl in ctrls: cmds.addAttr (ctrl, ln= attrName, proxy="%s.%s"%(mainCtrl, attrName), at="bool", keyable=1)else: cmds.addAttr (ctrls, ln= attrName, proxy="%s.%s"%(mainCtrl, attrName), at="bool", keyable=1)
Now, utilizing the Node Editor, we tie the visibility of the FK and IK controls together with the IKFK attribute, so that only the appropriate controls are displayed at a given time:
As our controllers are now in place, we can begin driving our bind chain (the original shoulder to wrist chain we duplicated). Using the Node Editor, we will connect the IK/FK chain’s individual joints’ rotation attributes into blendColors nodes, and pipe the respective output to the rotation input on the bind chain. For example, the l_shoulder joint will be driven by a blendColors node that receives both the l_fk_shoulder’s rotation in ‘Color 1’ and l_ik_shoulder’s rotation in ‘Color 2’, with the ‘Blender’ attribute connected to our custom IKFK attribute.
Note: This image omits the FK chain inputs in ‘Color 1’ and the IKFK attribute input in ‘Blender’ on the blendColors nodes.
Now we have an arm rig that allows for toggling of IKFK using the custom attribute on any given controller. By swapping the IKFK attribute on any controller, the rig will automatically pull the rotation values from the desired drive chain to the given bind chain, as well as updating the visibility of the controllers.
The Arms | Automation Process
In terms of automation, the largest obstacle to tackle is the lack of persistence of python data between Maya launches/scenes. Whilst there are a few options for devising a solution to this problem (such as Andrew Christophersen’s The Dual Power of Metanodes in Maya), I will be tackling this via Maya’s custom shelves, as I assume the joints will be following my own naming conventions, as well as considering that the scope of this project does not require such a versatile solution. For reference, I will be utilizing PyMel as well as the Maya API (OpenMaya 2).
To start, we will begin creating individual python functions that replicate the exact steps that we took in the manual process. Any tool or process we undertake within Maya will output the resulting MEL script that runs under the hood to preform a given task. Utilizing this, as well as the MEL and Python documentation given by Autodesk, we can convert the manual tasks into script (with a little math). For brevity, I will not list out the entirety of all the helper functions, however, I will place some relevant ones in the relevant scripts section below. This function in particular covers the majority of steps:
Python
defcreateIKFKRig(bindChain, prefix="l_"):# create duplicate joint chains ikChain = dupeJointChain(bindChain[0], bindChain[2], search=prefix, replace=prefix+"ik_") fkChain = dupeJointChain(bindChain[0], bindChain[2], search=prefix, replace=prefix+"fk_")# disable visibility of duplicated joint chains cmds.setAttr(f"{ikChain[0]}.visibility", False) cmds.setAttr(f"{fkChain[0]}.visibility", False)# create and store fk controllers fkCtrls = createControllers(selection=fkChain)# create and store ik controllers ikCtrls = [] ikCtrls.append(createController(selection=ikChain[2], removeConstraint=True))# create and store fk controllers ik_handle = createIKHandle(ikChain[0], ikChain[2], name=prefix+"ik_handle", newParent=ikCtrls[0])# create pole-vector locator, spawn controller at loc position, delete locator ik_pv_loc = create_loc(return_pole_vector_position(ikChain[0], ikChain[1], ikChain[2]), name=prefix+"ik_elbow")[0] ikCtrls.append(createController(selection=ik_pv_loc, removeConstraint=True)) cmds.delete(ik_pv_loc)# create pole-vector constraint on the pole-vector controller# create orient constraint on wrist controller cmds.poleVectorConstraint(ikCtrls[1], ik_handle) cmds.orientConstraint(ikCtrls[0], ikChain[-1])# create IKFK attribute on wrist controller createIKFKAttr(ikCtrls[0])# copy IKFK attribute by proxy onto other controls IKFKattrCopy(ikCtrls[0], fkCtrls) IKFKattrCopy(ikCtrls[0], ikCtrls[1], isSingle=True)# create and tie visibility nodes createControlVisDriver(ikCtrls, fkCtrls, ikCtrls[0], prefix+'arm')# create and tie blendColors nodes createBlendDriver(bindChain, ikChain, fkChain, ikCtrls[0])# toggleIKFK(bindChain, fkChain, ikChain, fkCtrls, ikCtrls, IKFKattrCtrl=ikCtrls[0])# return the pertinent datareturn ikChain, fkChain, ikCtrls, fkCtrls
Now, when we wish to create a new arm rig, we create a list of the arm’s bind chain joints, and return the data given back from the ‘createIKFKRig()’ function, as such:
Python
# set bind chain jointsl_arm_bindChain = ['l_shoulder', 'l_elbow', 'l_wrist']# create arm rig, and return pertinent datal_arm_ikChain, l_arm_fkChain, l_arm_ikCtrls, l_arm_fkCtrls = createIKFKRig(l_arm_bindChain, prefix="l_")
In terms of the persistence of data between instances of Maya, we create a custom shelf and create a user script as follows:
As I anticipate only myself working within Maya for this project, this is a viable solution. For reference, I am not including some of the extraneous data I keep track of, such as a list of the custom nodes we created earlier. Keeping track of this data ensures that when we wish to delete the entirety of a rig’s controls, that the relevant nodes are also destroyed.
The Challenges | Development Log
One of the first challenges I faced was finding a clear and concise workflow to base the automation off of. The most resourceful material I was able to find was Jason Baskin‘s youtube channel, which detailed the manual process of rigging a 3D character. Utilizing this workflow (along with Jason’s endlessly helpful information), I was able to create a basic arm rig manually.
The process of automation for the manual steps was actually rather easy, as I could simply reference the documentation for Maya’s Python scripting, and essentially just repeat the same steps I took during the manual process. Alongside this, there were the countless bugs / issues I had with interacting with the Node Editor, that were all user-error. One unique issue I encountered was the pole-vector position script, as I originally created my own Vector3 struct for doing vector math, and somewhere along the line realized that Maya’s API (OpenMaya) has its own form of Vectors that I could utilize, which saved me quite a bit of headache.
The largest challenges I faced within this process was actually the setup required for the skeleton joints, as the majority of information on the topic is rather surface level. Jason Baskin’s youtube channel did briefly go over the orientation of the joints and the importance of keeping chains planar if they require an IK Handle, however, I found myself working with non-planar joints for quite a while. The result of this was retrying different meshes, different math, and breaking down the entirety of the pole-vector placement math down multiple times to ensure that I am a sane person. After realizing that the joints were non-planar, I recreated the skeleton and finally got the desired effect.
Relevant Scripts | Development Log
This is the script for determining the position in which the pole-vector controller should sit for the elbow/knee. This script in particular is in reference to tdHendrix‘s youtube video “Maya Applied Math – Placing Pole Vectors“, in which we utilize some extra math to ensure that the pole vector position does not clip into the joint chain upon nearing max extension of the IK chain:
Python
# returns a pole vector position given three jointsdefreturn_pole_vector_position(rootJnt, midJnt, endJnt): start_vec = om.MVector(cmds.xform(rootJnt, q=True, ws=True, t=True)) mid_vec = om.MVector(cmds.xform(midJnt, q=True, ws=True, t=True)) end_vec = om.MVector(cmds.xform(endJnt, q=True, ws=True, t=True))# gets: the dir from start to end | the dir from mid to start start_end_mp_vec = (end_vec - start_vec) point_vec = (mid_vec - start_vec)# divide the dot-prod of the dir vectors by start to end dir ^^2 scale_val = (start_end_mp_vec * point_vec) / (start_end_mp_vec * start_end_mp_vec)# project the midpoint line by the result above + the original start vector proj_vec = start_end_mp_vec * scale_val + start_vec# get the length of the full chain root_mid_len = (mid_vec - start_vec).length() mid_end_len = (end_vec - mid_vec).length() total_len = root_mid_len + mid_end_len# loc pos = the normalized dir mid -> projected vector * a scalar + the mid posreturn (mid_vec - proj_vec).normal() * total_len + mid_vec
These functions allow us to align the IK and FK chains to each other, ensuring that we have IK/FK matching when toggling between them. For FK specifically, we copy the translation and rotation values of the IK joints directly to the FK controllers. Whereas for IK matching, we get the pole-vector position that would align with the current state of the FK joint chain, and snap the pole-vector controller to said position and delete the temporary locator. Following this, we copy the translation and rotation values for the wrist controller to the FK wrist controller:
Python
# allign fk chain to ik chaindefalignFK(fkControllers, ikChain):for fkControl, ikJoint inzip(fkControllers, ikChain): copyTransforms(ikJoint, fkControl, world=True) copyRotations(ikJoint, fkControl, world=True)# align ik chain to fk chaindefalignIK(ikWristControl, ikElbowControl, fkControls, fkChain): fk_pv_loc = create_loc(return_pole_vector_position(fkChain[0], fkChain[1], fkChain[2])) copyTransforms(fk_pv_loc, ikElbowControl, world=True) copyRotations(fk_pv_loc, ikElbowControl, world=True) copyTransforms(fkControls[2], ikWristControl, world=True) copyRotations(fkControls[2], ikWristControl, world=True) cmds.select(fk_pv_loc) cmds.delete()
For actually toggling between IK and FK, we flip the state of the custom IKFK attribute, retrieve the new state, and call ‘alignFK()’ or ‘alignIK()’ depending on the state. Since we are utilizing a node setup for toggling the visibility of the controllers, we do not need to manually toggle the controllers visibility attribute:
Python
# toggles the custom IKFK attribute and updates the driving chain automaticallydeftoggleIKFK(bindChain, fkChain, ikChain, fkCtrls, ikCtrls): toggleIKFKAttr(ikCtrls[0]) IKFKAttrVal = getIKFKAttr(ikCtrls[0])if IKFKAttrVal: alignFK(fkCtrls, ikChain)else: alignIK(ikCtrls[0], ikCtrls[1], fkCtrls, fkChain)
As for toggling the drive chain, we utilize this function to force override the connection between the desired drive chain’s joints rotation values and the bind chain:
Python
# connects the given drive chain's rotation attributes to the bind chaindefsetDriveChain(bindChain, driveChain, attrName="rotate"):for bindJoint, driveJoint inzip(bindChain, driveChain): cmds.connectAttr(f"{driveJoint}.{attrName}", f"{bindJoint}.{attrName}", force=True)