Unity Movement Basics Tutorial

October 6, 2020

Unity

Movement


Title: Move in Unity3D – Ultimate Unity Tutorial
By: Jason Weimann
Youtube – Tutorial
Description: Tutorial for covering the basics of all the different ways to move objects in Unity.


Overview

Movement is something I have worked with a lot in Unity as it is part of basically every project in some way or another. Being such a prevalent topic, I just wanted to make sure I had a good understanding of all the different ways to apply movement so I could pick the best options for specific projects. This tutorial is very basic on every front, but inclusive so I figured it was a good point to make sure I knew all the options. There was not a lot to learn from this tutorial for me, but it did help support some of the approaches I already use.

Tutorial Notes

Transform Based Movement

These approaches to movement deal with directly altering the transform values of an object, such as position and rotation, mathematically through general vector math. This generally the built in physics system and gives very tight and precise controls.

Move Transform Position With Input

This is the first basic approach of altering the transform.position value of objects directly. This used GetKeyDown (which only applies once per press) along with large value changes to create more segmented or tile based movement.

Move Transform Position With Input Limit Movement

Similar to the previous approach but it used a mathematical position check to limit the player’s movement. This kept the player’s positional value from getting too large or too small, which effectively creates boundaries without creating physical boundaries within the game.

Move Transform Position With Input Limit Movement Cleaned

This had the same exact logic as the previous approach, but used different syntax to be more readable. This included a strong focus on using expression body property methods to assign bool variables all within a single line of code.
Example:
private bool ShouldMoveBack => Input.GetKeyDown(KeyCode.DownArrow) && transform.position.z > -1;

Move Transform Position With Input Smoothly

This was the first approach to apply Time.deltaTime to the transform.position value to create much smoother movement. They swapped over the GetKey instead here to continuously apply the movement while the key is pressed. As usual they also applied a move speed value within the movement to help control the size of the incremental steps, and in turn the general speed of the object.

Move Transform Position With Input Smoothly And Rotation

Similar to the previous approach but they added rotation functionality. This was done simply by using Unity’s Rotate method along with a rotation speed value and Time.deltaTime to keep it smooth as well.

Force Based Movement

Move With Force

This started the use of the rigidbody component, which is necessary to use Unity’s physics system. They simply started with the rigidbody.AddForce method to apply force to the object within the physics system and cause it to move. Applying this to a cube however caused it to topple over and give awkward results since the force direction changed with the rotation of the cube.

Move With Force Use Tranform Rotation

To fix some of the issues they were having, they froze the rotation of the rigidbody on all axes so it could not rotate at all. Now when the force was applied the cube simply slid along the ground in the same configuration at all times. To allow it to rotate along the vertical axis of the world, they simply applied an internal transform.Rotate method.

Jump

They simply allowed a strong upwards force to be created with the AddForce method. This section was interesting as they once again covered the benefit of separating your player input reading into your Update method, while your physics application is done in FixedUpdate. They accomplished this by having the inputs in Update simply set bool values, and then FixedUpdate would read those bool values to determine if they should perform an action and what action it should be, and then the FixedUpdate would reset the bools if they performed their action. This helps keep the physics running consistently and smoothly while removing the possibility of inputs being missed or eaten by the player.

Move With Force Transform Rotation Clamp Velocity

This option prevented force from being able to be applied when the velocity of the object passed a certain value. This however is a weird soft cap, because force and velocity are not extremely tied together. Force applies an acceleration which in turn alters the velocity of the object. This means that the velocity can hit a range of different values passed the cap (hence the soft cap) depending on how much force is applied in the instances leading up to the object reaching the velocity cap.

Character Controller

While this is mostly tied to rigidbody components, it felt like its own varied option for movement. This is a component provided by Unity which helps get the basics of a player controller going for you. Along with the basics of setting up movement, it also has some additional features such as slope detection and elevation/step detection.

Navigation Mesh

They really just covered the bare minimums of using a Navigation Mesh to help you move a character around. This also is not something I am focused on using in my next major project so I did not need this section for now.

Animation

This focused on how you can use Unity’s Animation window to provide movement to objects. You create an animation for an object, and then you can select “Record” and save various parameters of the object at various times as key frames for an animation. While the focus was on changing the object’s transform.position values to animate movement, this can be done with any values such as scale or color even. This does not give a lot of variability, but can be useful to quickly get something moving with a repeating pattern in the environment for example.

Summary

As expected there was not a whole lot of new information I got from this tutorial, but it did help me organize the different options in my head better. It also provided yet another point of support on the separation of input and application to movement through the Update and FixedUpdate methods again in the Jump section so that was good to see. That separation is definitely something I will be using moving forward with my own projects.

Newer Unity Input System

October 5, 2020

Unity

Input Systems


Title: NEW INPUT SYSTEM in Unity
By: Brackeys
Youtube – Tutorial
Description: Tutorial for using Unity’s newer input system.


Overview

This setup uses Unity’s improved new input setup system. It provides a nice way to setup your inputs more specifically without directly going into the Project Settings -> Input Manager window. The user starts with a blank slate and adds actions to this input manager asset to match up with all the actions they will want in the game.

From this tutorial they obtained the tools to use this new input system through a project on github, but now it is available as a standard package within Unity simply named Input System. It however mentions that the backend has been modified (I am using Unity version 2020.1.5f1 currently when testing this) so I am keeping an eye out for any problems it may cause.

Tutorial Notes

There are three major sections to this input system: Action Maps, Actions, and Properties. The action maps appear to be like keybinding sets, so you can save entire different sets of actions with their own keybindings to each map you create. Then the actions are the core focus, where actions can be named and keybindings can be set, as well as which types of controllers are used. Finally the properties section allows for more detailed additions to each action such as other modifiers to apply to the input when used as well as the type of action.

After filling this out to the desired result, there is an option to “Generate a C# Class” from this new input system you have created. This provides you with the proper tools to utilize the asset you created within your programming system yourself. The context is a bit more awkward as it uses events, so you have to assign methods to them when using them in your own programming. They set this up in the Awake method for example:

controls.Player.Shoot.performed += _ => Shoot()

controls is the name of the InputMaster object (which is what they named the generated C# file from the input system), Player is the name of the action map, shoot is the name of the action from the input system, performed is a subset of that action, and finally Shoot is the method being subscribed to that event. The underscore is simply a place holder used for this programming syntax so it is necessary but I am unsure exactly why the syntax is like that.

I was then having an issue following the tutorial because they simply made controls (their InputMaster object) public so they could drag/drop the input system asset itself directly into the component so they were connected and running. When I did this the InputMaster object did not show up in my Inspector, even when made public. To get it to work at all, I found that I just needed to assign a new InputMaster to controls in the Awake method. I found that in the documentation provided here: Unity New Input System Manual

I then found that natively you could not use both the old input system and the new input system at the same time. So while this did get the new input system working and I could jump (which was the only action I assigned for testing), I could not move horizontally at all as the inputs for that just did not work anymore. Exploring the documentation further, I did find that you can switch back and forth between the old and new input system, as well as activate both at the same time, in the: Project Settings > Player, under: Active Input Handling. Upon setting that to both, I could move horizontally (with the old inputs) and jump (with the new inputs).

Installation Guide here: Unity New Input System Installation and Setup Documentation

Summary

This approach seems promising for setting up complex keybinding setups where you also want multiple devices. It does provide the base benefit of not needing to use strings with the input system anymore when doing the programming so that is a large benefit already. I would have to explore how to edit keybindings at runtime with this setup to see if it is a good final approach for this system that would also support letting the player set their own keybindings.

Unity Create Your Own Keybindings Manager

October 5, 2020

Unity

Input Systems


Title: How to Create a Custom Keybinding Handler for your Unity Game – *Improved*
By: Dapper Dino
Youtube – Tutorial
Description: Tutorial for creating your own basic input manager within Unity.


Overview

The idea behind creating an input manager is to have a flexible and easily accessible tool for both setting up your input system within a game as well as modifying it. This manager should help keep programming associated with the player input more organized and consistent, as well as providing pathways to allowing both the designer and eventually the players options to easily change the inputs to their liking.

Tutorial Notes

Setup

Immediately they create an InputManager class that follows a singleton pattern, but also includes a DontDestroyOnLoad method. This is ok to start, but may be worth looking into editing that if using a more sophisticated multi-scene project setup later on.

Within the InputManager, they created classes to replace some of Unity’s basic input reading methods. These included: GetKey, GetKeyDown, and GetKeyUp.

They then added another class named KeybindingActions, which was a container for a public enum that held references to all the possible actions you may want for the game. For now I decided to just include this enum directly in the InputManager class, but will see if it makes sense to separate later.

Next they add the scriptable object core of this setup, which is named Keybindings. The benefit of using a scriptable object here is that it makes it easy to swap it out with different sets of keybindings (especially with different types of input or controllers).

Building Out InputManager and Keybindings Scriptable Object

Within this scriptable object, they created another class named KeybindingCheck. This provides the connection to setup which keys are tied to which actions. They mention a dictionary could be used here, but they created a list of this serializable class instead so it can easily be seen and modified within the Inspector. This class simply holds data for a KeyBindingActions object and a KeyCode object (to ensure they are connected). The scriptable object then just has a list of these KeyBindingChecks.

They mention if you want the player to be able to set their own keybindings you technically just need to edit the scriptable object and this will modify the keybindings. However, scriptable object changes only remain if they are done in the inspector, so you would also need to save that data somewhere else if you had a game where you want the player to be able to set their keybindings once and have the same setup each time they close and reopen the game, which would be the standard implementation.

With that setup, they go back to fill out the methods within the InputManager which effectively replace those provided by Unity. Each of them follow the same pattern seen here in the GetKeyDown replacement method:

public bool GetKeyDown(KeyBindingActions key)
{
foreach (KeyBindings.KeyBindingCheck keyBindingCheck in keybindings.keyBindingChecks)
{
if (keyBindingCheck.keyBindingAction == key)
return Input.GetKeyDown(keyBindingCheck.keyCode);
}

return false;
}

So effectively whenever you would use GetKeyDown for example, you use this InputManager.GetKeyDown method and pass in one of the enum options you have provided as a parameter (i.e. Jump, Crouch) and it searches through the list of KeyBindingCheck objects you have in the KeyBindings scriptable object and if it finds that enum in that list, it returns the Unity base input method (i.e. GetKeyDown here) with the corresponding keyCode you have associated with that enum as its input parameter.

Summary

I like that this method allows for the use of easily accessible and modifiable enums that are specifically chosen for your game when it comes to programming the input of your game, but I am concerned how efficient this is since it appears to add small extra checks with every single input from this user. While small, this is an extremely common action that will be used thousands and thousands of times easily in normal gameplay so I wonder if it ends up being worth the cost. This method does also allow you to edit the keybindings at runtime and because it is with a scriptable object, the changes are actually saved even when exiting play mode.

Brackeys 2D Movement and Melee Combat Tutorials – 2D Movement

September 30, 2020

Unity

2D Movement


Title: 2D Movement in Unity (Tutorial)
By: Brackeys
Youtube – Tutorial #1
Description: Tutorial for using a simple Unity player controller.


Title: MELEE COMBAT in Unity
By: Brackeys
Youtube – Tutorial #2
Description: Tutorial for setting up basic melee combat with a 2D player controller.


Overview

I started with the Melee combat tutorial but it referenced the movement tutorial for how they setup the starting movement and animation so I wanted to move back to them just to make sure I was starting in a similar spot. The player controller made in the 2D movement tutorial is actually pretty bad unfortunately, but I still wanted to use this melee combat tutorial as a base point for something that is workable but not amazing just to get an idea of how to approach combat.

2D Player Movement – Tutorial #1

While overall not a great tutorial, it did support some concepts I have come across. They separated the player input functionality and the actual movement application into the Update and Fixed Update methods respectively, which is a solid approach I have seen more and more in my search for information on player controllers now. However, all of the Fixed Update work was basically already done in a Player Controller script they gave you, so it really just covered programming the script responsible for receiving player input and passing it on to the movement logic.

To make matters worse, the given script does not even work particularly well. Its checks for the ceiling and the ground can give weird results unless at good ranged values which can prevent your player from crouching or jumping, or getting out of crouch at times. Then when air control is turned on, there is a bug where the character automatically crouches in midair (which removes their upper hitbox) simply from them jumping into objects as the ceiling sensor activates and automatically makes them crouch in the air.

I was able to fix the midair crouching bug by adding an extra check in the tutorial given script to also ensure the player was grounded before making crouch true. This led to another interesting aspect of the tutorial with the separation of input and actual player movement because the movement was receiving information from the input such as “is crouch being pressed” and then would use that information and check the surroundings (such as if they are under a ledge) to determine whether they could actually move out of crouch or not. This was just an interesting way of separating the input logic from the actual player control logic and is good to keep in mind for an input buffering system.

After fixing the bugs and messing with adding some animation similar to what they already have at the start of the melee combat tutorial, I did not have time to move on to that one. I will look into completing that next with my decent player controller in place now with most of the animations.

Unity Custom Keybinding Manager

September 29, 2020

Unity

Keybinding Manager


Title: How to Create a Custom Keybinding Handler for your Unity Game – *Improved*
By: Dapper Dino
Youtube – Tutorial
Description: Tutorial for setting up an input manager scriptable object in Unity.


Overview

I was looking for a nicer way to control inputs and controls when setting up a Unity project other than the very basic way of listing out all the specific key codes in the user scripts themselves or using fragile string references when tying it to Unity’s natural input manager. Initially I came across this creator’s first attempt at setting up a keybinding handler (hence the *Improved* tag on the title of this tutorial) but was not as interested in it since they still used strings and I thought an enum implementation would be better, but lo and behold, the same creator had actually improved their system a year later with an enum system like I was imagining.

While maybe not perfect, I do still like this overall implementation better than just using Unity’s natural tools for sure. Adding the enum setup removes the necessity of typing in direct and exact strings in your code which is great for reliability, while also making it easy to change key bindings in the scriptable object itself during develop. Having a system like this is also a good start for a truly accessible product on release that allows users to set their own keybindings, which is standard in many games.

Unity Fixed Update Purpose

September 25, 2020

Unity

Fixed Update


Title: GameDev Stream — What is FixedUpdate For?
By: Infallible Code
Youtube – Information
Description: Quick rundown of the main purpose of using fixed update in Unity.


Overview

This video quickly covers the main purpose of using FixedUpdate in Unity. As most Unity users know this is commonly used for containing physics calculations, but they better describe why that is here. They explain that FixedUpdate is much more consistent as it is inherently time based, whereas Update is tied directly to frame rate, which can vary drastically from computer to computer or user to user. This consistency however is what also makes FixedUpdate bad for uses such as user input because they could basically be entering inputs between the FixedUpdates and they will not be picked up at all, which is obviously extremely bad.

Unity Scriptable Objects Tutorial Updated

September 24, 2020

Unity

Scriptable Objects


Title: Better Data with Scriptable Objects in Unity! (Tutorial)
By: Unity
Youtube – Tutorial
Description: Quick updated rundown by Unity themselves on using Scriptable Objects.


Title: Scriptable Object Unity Documentation
By: Unity
Unity – Documentation
Description: One of the suggested links to follow from the tutorial video that is just the official documentation on scriptable objects.


Title: Making cool stuff with ScriptableObjects
By: Matt Schell
Unity – Blog
Description: Another suggested link to follow from the tutorial video showing some more examples of using scriptable objects.


Overview

I wanted to make a quick reference to this new video as it was just released yesterday (Sep 23, 2020) and I have wanted to explore scriptable objects in Unity and getting recently updated information is always useful.

Scriptable Objects as Data Containers

Scriptable Objects can be useful tools as data containers as is shown in their example using them for cards in a card game. They explain they can be a better option here than a Monobehaviour because Monobehaviours must be attached to a gameobject, where as Scriptable Objects can be used similarly to regular objects in that they do not have this requirement. If data does not belong to an instance, but is more shared amongst game objects, it is better to store it in a scriptable object. This is because when Monobehaviours reference Scriptable Objects they store a reference that points to the scriptable object as opposed to making their own copy of the data.

Scriptable Objects as Enum States

Scriptable Objects can also be used to author extended Enum states. They explain this through an example where they have a Placeable Data scriptable object which has Enum options for their Attack Type and their Target Type. This appears to just mean they support Enum lists which then allow for an easy dropdown option in the Inspector (similar to how Enums generally work in my experience).

Runtime Data Editing

They expand on the benefits of using scriptable objects as extended Enum states is that they allow for real time data editing (while in play mode). Normally most edits made in the Unity Editor during play mode are not saved so you have to remember them and reapply them if they are changes you want. Scriptable objects however can have their edits during play mode saved on the spot so they will persist even after leaving play mode. This is because scriptable objects are not bound to a scene’s runtime, they exist on a project basis in the Assets folder.

Reference List for Creating State Machines in Unity with Focus on Character Controllers

September 23, 2020

State Machines

Unity and Character Controller Focus


Title: The State Pattern (C# and Unity) – Finite State Machine
By: One Wheel Studio
Youtube – Tutorial #1


Title: How to Code a Simple State Machine (Unity Tutorial)
By: Infallible Code
Youtube – Tutorial #2


Title: Complex Enemy Behavior using Finite State Machines – 2D Platformer – Part 13 [unity]
By: Bardent
Youtube – Tutorial #3


Title: State Machine Setup – 2D Platformer Player Controller – Part 21
By: Bardent
Youtube – Tutorial #4


Title: Movement State Machine – Free download
By: Epitome
Youtube – Tutorial #5


Title: Unite 2015 – Applied Mecanim : Character Animation and Combat State Machines
By: Unity – Aaron Horne
Youtube – Tutorial #6


Overview

I have dealt with using state machines before, but mostly for creating AI systems. I wanted to investigate using a state machine specifically for a player controller, focused on 2D player controllers if possible. With this in mind, I just gathered many resources on more general state machine concepts and design with a mix of more player controller focused examples when possible.

The quick breakdown is as follows:

  1. Tutorial #1 – General Finite State Machines
  2. Tutorial #2 – General Finite State Machines
  3. Tutorial #3 – AI Finite State Machines
  4. Tutorial #4 – Player Controller Finite State Machines
  5. Tutorial #5 – Player Controller Finite State Machines
  6. Tutorial #6 – Player Controller/General Finite State Machines

Tutorial #1

This is a great quick tutorial on Finite State Machines and implementing them in general in C# and Unity. It covers the various levels of state machine implementations and the pros/cons of each tier of state machine organization. This is a fantastic starting point for state machines.

Tutorial #2

This tutorial is a more general state machine but it does still have a focus on turn based gameplay. While I was focused on player controller FSMs, I am also interested in how to use these for game states in turn based play so I wanted to record this.

Tutorial #3

This tutorial focuses more on AI FSMs, which I have more experience with, but I still wanted to grab a reference to this as a decent looking tutorial on implementing an FSM in general. I also have another Bardent tutorial that is a player controller focused FSM so I thought this also might help me tie in my prior experience if I followed this approach.

Tutorial #4

As mentioned above, I have two tutorials from the same tutorial set and this is the second. I am hoping there is an overlap in the two systems that I can also take away from by observing what they are able to recycle between them. I also hope this will help make this FSM make more sense since I can tie in my prior AI FSM experience.

Tutorial #5

This is a quick tutorial that directly shows the setup for a player controller FSM. It appears that it might not be the ideal architecture I am looking for, but it could still serve as a good example when starting to design a player controller FSM.

Tutorial #6

This older (from 2015) Unite talk goes a bit more in depth into the combination of character animation and combat state machines. This could be a strong next step for me to look into after focusing on movement for the core of the player controller state machine. I am especially interested in seeing if I can implement their combat combos with their FSM approach in some capacity, as well as if they have an input buffering design I can learn from.

2D Melee Combat Tutorial and Game Kit with Thomas Brush

September 22, 2020

Game Development

2D Melee Combat

How To Make 2D MELEE COMBAT (Unity Tutorial + Free Game Kit!)

Youtube – Link

By: Thomas Brush


Referenced Previous Tutorial
How To Make 2D Platformers (Unity Fundamentals Tutorial)

Youtube – Link

By: Thomas Brush


First Portion

Camera

They start by using a VirtualCamera game object from the Cinemachine package within Unity. This camera object gives a lot of useful camera controls without having to build another from scratch. They mention another tutorial to help with paralaxing, so this may not be included in the virtual camera.

Character Animation

Spine

This seems to be the major animator they used, so this may be something worth looking into as I have come across it a lot now. For animation tips, they suggest strong bouncing effects on the vertical axis (squashing and stretching majorly in the y-axis generally, with some distortion in the other axis). Spine also gives you the option of different skins to provide the same set of animations to similar character type objects.

Animation State Machine

Again they reference a previous tutorial covering this more in depth. They do show how their animation system fires events to help perform certain actions in tandem with the animations without necessarily adding more programming. Examples for this include emitting particles or playing a sound on animation start or end.