Driving a Forklift with the New Input System in Unity 2021
In this article we’ll look at using the new Input System for driving and controlling a forklift.
Our Action Map is pretty straight-forward.
We have the obligatory 2D Vector Move Action, a 1D Axis (Positive/Negative) Secondary Movement Action for the tongs, and a standard button for the Exit Action.
Our Forklift script resides on the forklift game object.
As usual, I’ve highlighted just the input related variables and using statement here.
Just commenting on the input related code here, we can see our Start() method assign the _inputActions variable with a copy of the InputActions script that was generated by the Input System Mapping asset.
We add a subscriber/listener method for when the Exit Action occurs to disable the Drive Action Map.
In the EnterDriveMode method the Drive Action Map is enabled.
While not seen here, in another script the Character Action Map is disabled before the EnterDriveMode() method is called and then the Character Action Map is enabled after the ExitDriveMode() method is called.
In the Update() method we can see two movement related methods, LiftControls for the tongs and CalculateMovement for the forklift itself are being called.
We can also see the legacy input code that is checking every frame for the escape key which has been replaced with our ExitOnPerformed() subscriber method.
In the LiftControls() method called from the Update() method, we check if the SecondaryMovement Action is currently being triggered, and if so we use ReadValue to determine the positive or negative input of this 1D Action.
We can also see in the commented out code the previously used legacy input which is now not necessary.
These are the methods then called to either lift or lower the tongs of the forklift.
There is no new input code here, but I wanted to add it so that everyone can see the actually transform related code for accomplishing this task.
Last, we have the CalculateMovement() method with new input code and legacy input code for effect.
With the 2D Vector value, we are dealing with an X&Y value that determines WASD input:
W: 0,1 | S: 0, -1 | A: -1, 0 | D: 1, 0
We can see that the original code is well suited for simple drop-in replacement of the values from the new Input System values.
Instead of “v” for vertical or W&S keypresses, we have “inputMovement.y”.
Instead of “h” for horizontal or A&D keypresses, we have “inputMovement.x”.
Note that existing code may not in all cases be normalized as the inputMovement.x and y values are.
If you are having an issue with too much or too little effect directly related to these values that is probably the cause.
That’s it for this article.
In the next article I’ll go over how to determine the specific interaction type of an Action from code.