Implementing touch with Input System's Enhanced Touch API
The project already includes a BuildManager
script. Again, take a moment to look at what each method does. Here’s a breakdown of the key points:
Most of these methods work behind the scenes. The only two you need to interact with are MoveAsset
and Build
. InputManager
calls MoveAsset
. The UI Event System calls Build
. Now that you understand how BuildManager
operates, it’s time to add the last bit of code to InputManager
.
InputManager
interprets the players intent through their touch actions. There are three stages in total:
OnPointerDown
event that starts the building process. It passes the details to BuildManager.Build
.BuildManager.MoveAsset
.BuildManager.PlaceAsset
.Add each of the stages. First add a new class variable above the Awake
method:
private bool isBuilding;
Second, add a new method:
public void StartBuildOnPointerDown(GameObject model)
{
if (Touch.activeTouches.Count == 0)
{
return;
}
isBuilding = true;
BuildManager.Instance?.Build(model,
Touch.activeTouches[0].screenPosition);
}
StartBuildOnPointerDown
is called through an Event Trigger setup on the Well and WoodCutterLodge UI game objects. If the finger is still touching the screen, then isBuilding
is set to true for tracking. It wraps up by passing the model and screenPosition of the finger to BuildManager.Build
for processing. Finally, add the DragAsset
and CompleteBuild
methods:
public void DragAsset(Touch touch)
{
if (touch.phase != TouchPhase.Moved)
{
return;
}
BuildManager.Instance?.MoveAsset(touch.screenPosition);
}
public void CompleteBuild()
{
isBuilding = false;
BuildManager.Instance?.PlaceAsset();
}
Here’s what these methods do:
DragAsset
is a pass through method. It uses TouchPhase.Moved
to confirm the finger moved during the frame. Then it passes the new screenPosition to BuildManager.MoveAsset
for processing.CompleteBuild
is only called if the finger leaves the screen. It toggles off build mode and notifies BuildManager
.There’s one final change: You need to update Update
. :] Replace all the code in Update
with the following:
//1
if (Touch.activeFingers.Count == 1)
{
if (isBuilding)
{
DragAsset(Touch.activeTouches[0]);
}
else
{
MoveCamera(Touch.activeTouches[0]);
}
}
//2
else if (Touch.activeFingers.Count == 2)
{
ZoomCamera(Touch.activeTouches[0], Touch.activeTouches[1]);
}
//3
else if (Touch.activeFingers.Count == 0 && isBuilding)
{
CompleteBuild();
}
Now Update
looks for three key conditions:
Save your changes and return to the Unity editor.