Input
Ensure you use Project Settings ⇒ Player ⇒ Input Handling ⇒ Both, or multiple errors may occur.
Input Concept
The input in NWH Vehicle Physics 2 revolves around InputProvider
s. These scripts obtain user input from different sources such as InputSystem or Rewired (e.g. keypresses, mouse movement, gamepad input, etc.), process it, and pass it on to the vehicles.
Multiple InputProvider
s can coexist, allowing for e.g. MobileVehicleInputProvider
, InputSystemVehicleInputProvider
, and SteeringWheelVehicleInputProvider
to be present simultaneously. Input from all InputProvider
s is combined.
Input Retrieval
The diagram above illustrates the path from the input source to the vehicle input state:
- Input is obtained from hardware through Input Sources (green). This can be input from any method available in Unity. In this example, InputManager (old/standard Unity input), touchscreen/sensors (mobile input), and LogitechSDK for steering wheel input are used.
- InputProviders pass this input to the vehicle (VehicleController.InputHandler). Input from all sources is combined and processed based on settings for the specific vehicle.
- If
Auto Set Input
is set to true, the state of the corresponding input for the vehicle in question will be set to the combined value of all inputs. - If the VehicleController has
Input > AutoSetInput
set to false, the new input will be discarded. This occurs when the vehicle is inactive or when the input is set by another script (e.g., AI).
Notes
- A single InputProvider supplies input for all vehicles, so it is recommended to have only one InputProvider of a particular type (e.g., one desktop and one mobile input provider, allowing vehicles to receive both desktop and mobile input simultaneously).
- Input providers only provide input; they do not set it. Vehicles acquire input from input providers if
autoSetInput
is enabled on them. - All InputProviders inherit from either
VehicleInputProvider
(for vehicle-related input) orSceneInputProvider
(for scene-related input, such as cameras). Thus, it's best to consider InputProviders as a standardized interface between different input methods and a vehicle. InputProvider
s are divided into VehicleInputProviders and SceneInputProviders. VehicleInputProviders transmit vehicle input (throttle, brakes, etc.), while SceneInputProviders handle scene input (vehicle changing, camera changing, camera movement, and other inputs not directly related to the vehicle). One of each is necessary (e.g.,InputSystemVehicleProvider
andInputSystemSceneInputProvider
).- Input is stored inside the
InputStates
struct and can be copied from one vehicle to another if needed. For example, this is done when a trailer is connected to a towing vehicle. - To manually set the
InputStates
, ensureautoSetInput
is set to false.
Available Bindings
Vehicle Input Provider Bindings
Out of the box gamepad bindings are only available for InputSystem.
Name | Type | Keyboard Defaults | Gamepad Defaults | Description |
---|---|---|---|---|
Steering | axis [-1,1] | A/D | Left Stick - Left/Right | Steering. |
Throttle | axis [0,1] | W | Left Stick - Up, Right Trigger | Throttle. |
Brakes | axis [0,1] | S | Left Stick - Down, Left Trigger | Brakes. |
Clutch | axis [0,1] | Manual clutch. 0 for disengaged and 1 for engaged. | ||
Handbrake | axis [0,1] | Space | B (Xbox) / Circle (PS) | |
EngineStartStop | Button | E | ||
ShiftUp | button | R | Right Shoulder | |
ShiftDown | button | F | Left Shoulder | |
ShiftIntoR1 | button | ` | Shift into 1st reverse gear. | |
ShiftIntoN | button | 0 | Shift into neutral. | |
ShiftInto1 | button | 1 | Shift into 1st forward gear. | |
ShiftInto[n] | button | 2,3,4,etc. | Shift into [n]th gear. | |
LowBeamLights | button | L | Y (Xbox) / Triangle (PS) | |
HighBeamLights | button | K | ||
HazardLights | button | J | ||
ExtraLights | button | ; | ||
LeftBlinker | button | Z | ||
RightBlinker | button | X | ||
Horn | button | H | ||
Module Bindings | ||||
FlipOver | button | M | Used for FlipOverModule. | |
Boost | button | Left Shift | A (Xbox) / X (PS) | Used for NOSModule. |
Cruise Control | button | N | Used for CruiseControlModule. | |
TrailerAttachDetach | button | T | X (Xbox) / Square (PS) | Used for Trailer and TrailerHitch modules. |
Scene Input Provider Bindings
Name | Type | Keyboard Defaults | Gamepad Defaults | Description |
---|---|---|---|---|
ChangeCamera | button | C | Start | Changes camera. |
CameraRotation | 2D axis | Mouse Delta | Right Stick | Controls camera rotation. |
CameraPanning | 2D axis | Mouse Delta | Right Stick | Controls camera panning. |
CameraRotationModifier | button | Mouse - LMB | Right Stick Press | Enables camera rotation. |
CameraPanningModifier | button | Mouse - RMB | Left Stick Press | Enables camera panning. |
CameraZoom | axis | Mouse - Scroll | D-Pad Up/Down | Camera zoom in/out. |
ChangeVehicle | button | V | Select | Change vehicle or enter/exit vehicle. |
FPSMovement | 2D axis | WASD | Left Stick | Demo FPS controller movement. |
ToggleGUI | button | Tab | Toggles demo scene GUI. |
Input Methods
Input Manager (Old/classic)
- Type of
InputProvider
for handling user input on desktop devices through keyboard and mouse or gamepad. - Uses old Unity InputManager. For new projects, it is recommended to use the Unity's new InputSystem instead as InputManager is becoming obsolete.
Since v1.1 InputSystem package is required even if not used. If using the old/classic Unity input set Project Settings ⇒ Player ⇒ Input Handling to Both
and proceed as normal. InputSystem package being present installed will not interfere with old/classic Unity input / InputManager.
Installation
When first importing NWH Vehicle Physics 2 the project will be missing required bindings. There are two ways to add those:
- Manually adding each entry to the Project Settings ⇒ Input following the input bindings table available here.
- Copying the contents of InputBindings.txt and appending them to the contents of the
[UnityProjectPath]/ProjectSettings/InputManager.asset
file. To do so:- Close Unity.
- Open InputManager.asset in Notepad/Notepad++/Visual Studio or any other text editor of your choice.
- Copy the contents of the provided InputBindings.txt file (Scripts ⇒ Vehicle ⇒ Input ⇒ InputProviders ⇒ InputManagerProvider ⇒ InputBindings.txt) and paste them at the end of the InputManager.asset. Make sure there are no empty lines between the existing content and the pasted content. Save the file.
- Open Unity. Check Project Settings ⇒ Input. The input bindings for NWH Vehicle Physics will appear towards the bottom of the list.
Scene Setup
To set up InputManager-based input in the scene add the following components to the scene:
- 'InputManagerVehicleInputProvider'
- 'InputManagerSceneInputProvider'
Any vehicle that is present in the scene will now receive input from these providers.
Input System (new)
- Since v1.1 NWH Vehicle Physics 2 has moved to InputSystem as a default input method.
- InputSystem v1.0 or higher is required. This is available in Unity 2019.3 or newer.
When using DS4Windows, InputSystem will detect button presses twice.
Installation
- Install 'Input System' package through Window ⇒ Package Manager
- Under Edit ⇒ Project Settings ⇒ Player ⇒ Other Settings ⇒
Active Input Handling select
Input System Package (New)
orBoth
- the latter in case your project still usesUnityEngine.Input
somewhere.
Scene Setup
- Add
InputSystemVehicleInputProvider
andInputSystemSceneInputProvider
to any object in your scene. - Default bindings can be modified by double clicking on
.inputactions
files.Save Asset
must be clicked for the changes to take effect.
Rewired Input Provider
Since v1.7.1 NWH Vehicle Physics 2 also supports Rewired input.
Installation
- Download and import Rewired from the Unity Asset Store.
- Follow the Rewired install wizard. Make sure to leave both InputSystem and InputManager enabled. To use only InputManager, as recommended by Rewired, InputSystemVehicleInputProvider and InputSystemSceneInputProvider and their respective editor scripts need to be removed from the project first.
- With the Rewired imported and installed, double click on NWH ⇒ Vehicle Physics 2 ⇒ Scripts ⇒ Optional Packages ⇒ Input ⇒ Rewired to import files needed for Rewired/NVP2 integration.
- Open the newly imported Rewired folder and add
Rewired Input Manager
to the scene. It already contains the RewiredInputManager
, as well as theRewiredVehicleInputProvider
andRewiredSceneInputProvider
needed for NVP2 control. - Remove any existing
InputSystemVehicleInputProvider
,InputManagerVehicleInputProvider
,InputSystemSceneInputProvider
andInputManagerSceneInputProvider
scripts from the scene to prevent input duplication. All these can technically be present at the same time but there are no benefits to it and duplicate inputs might happen.
Mobile Input Provider
- Add
MobileVehicleInputProvider
andMobileSceneInputProvider
to the scene. - Create a few UI ⇒ Button objects inside your canvas. Make sure that they are clickable.
- Remove the
UnityEngine.UI.Button
component and replace it withMobileInputButton
.MobileInputButton
inherits fromUnityEngine.UI.Button
and addshasBeenClicked
andisPressed
fields which are required forMobile Input Provider
- Drag the buttons to the corresponding fields in the
MobileVehicleInputProvider
andMobileSceneInputProvider
inspectors. Empty fields will be ignored.
Steering Wheel Input Provider
For more info visit SteeringWheelInputProvider page.
Scripting
Retrieving Input
Since v1.0 multiple InputProvider
s can be present in the scene, meaning that their input has to be combined to get the final input result. To get the combined input use:
float throttle = InputProvider.CombinedInput(i => i.Throttle()); bool engineStartStop = InputProvider.CombinedInput(i => i.EngineStartStop());
Or to get the input from individual InputProvider
s (say to find out if a button was pressed on a keyboard):
float throttle = InputProvider.Instances[0].Throttle;
Manually Setting Input
Input in each vehicle is stored in InputStates
struct:
myVehicleController.input.states
In case input should not be retrieved from user but from another script - as is the case when AI is used - autoSetInput
should be set to false
. This will disable automatic input fetching from the active InputProvider
.
Input now can be set from any script:
myVehicleController.input.Horizontal = myFloatValue; // Using getter/setter.
myVehicleController.input.states.horizontal = myFloatValue; // Directly accessing states.
When using input generated by code (i.e. AI) it is usually handy to have access to a single axis throttle/brake. This can be done like so:
vehicleController.input.autoSetInput = false; // Tells the vehicle to stop retrieving input values automatically. vehicleController.input.Vertical = 0.5f; //Sets throttle to 0.5f, resets brakes. vehicleController.input.Vertical = -0.5f; //Sets brakes to 0.5f, resets throttle.
vehicleController.input.states.throttle
is equal to vehicleController.input.Throttle
. The latter is just a getter/setter for convenience.
The alternative to this is using the inputModifyCallback
. It is executed just after the input is retrieved by the vehicle and allows modifying the inputs without having to worry about them being overwritten before the end of the frame:
myVehicleController.input.inputModifyCallback.AddListener(MyInputModificationFunction); --- private void MyInputModificationFunction() { vc.input.Handbrake = 1f; // Apply handbrake by overriding the user input. }
Custom InputProvider
If a custom InputProvider
is needed it can easily be written. Custom InputProviders
allow for new input methods or for modifying the existing ones. E.g. if the MobileInputProvider
does not fit the needs of the project a copy of it can be made and modifications done on that copy. That way it will not get overwritten when the asset is updated.
Steps to create a new ''InputProvider''
- Create a new class, e.g.
ExampleVehicleInputProvider
and make it inherit fromVehicleInputProvider
class:
public class ExampleVehicleInputProvider : VehicleInputProvider{}
- Override the methods that you want to use, e.g.
GetThrottle()
. - The required methods are abstract and will need to be implemented. There are also virtual methods such as
ToggleGUI()
which are optional and will be ignored if not implemented. - Methods that are not used should return
false
,0
or-999
in case ofShiftInto()
method. - The newly created
ExampleVehicleInputProvider
now can be added anywhere in the scene as the includedInputSystemVehicleInputProvider
orInputManagerVehicleInputProvider
would be.
Example custom input script is below. Note that to reference NWH.Common.Input the script will either need to be generated inside Scripts > Input folder of the asset or referenced inside the project .asmdef file if the script is placed outside of the VehiclePhysics directory. For more info about assembly definitions check out the Import guide.
Example Custom VehicleInputProvider
using NWH.Common.Input; using UnityEngine; using UnityEngine.InputSystem; /// <summary> /// Example class for handling input. /// </summary> public class CustomVehicleInputProvider : VehicleInputProviderBase { public override void Awake() { base.Awake(); // Your initialization code here (if needed). Just a standard MonoBehaviour Awake(). } public void Update() { // Your Update() code here (if needed). Just a standard MonoBehaviour Update(). } public override Throttle() { // Return your custom value here, example: return 0.5f; // Replace this line with e.g. player.GetAxis("Throttle") for Rewired. } public override Steering() { // Return your custom steering value here. return 0.123f; } // ...and so on. Override the functions that you want to use. If you do not need Clutch() for example, // do not override it. }