Connect Pieces Puzzle with Unity New Input System
Let’s create a puzzle where you connect pieces in a mold.
Before starting remember to install the Input System from Package Manager.
And change the Active Input Handling to either “Both” or
“Input System Package (New)”
Edit → Project Settings → Player → Other Settings → Configuration
These are the things you need:
- Camera
- Game Objects to move (with Colliders)
- Empty Game Objects as Transforms (Snap Points)
- Script to attach to the movable Game Objects
Create Input Actions
- Mouse right → Create → Input Actions
- Name it to PuzzleActions
- Open it and create an Action Map named Connect Puzzle with 2 actions (Shown below)
- Press Action Type is Button
- ScreenPos Action Type is Value and Control Type is Vector2
- Add bindings to the Press and ScreenPos using the + icon with the right Path. (You don’t need the Touchscreen ones)
- Save Asset and close
- Select the Input Action Asset and click the box “Generate C# Class” and hit Apply.
Let’s start creating the script (PuzzleInteractable)
Namespaces and variables that we need
(We will add read only Vector3 and boolean next)
Under the Vector3 curScreenPos we add Read Only Vector3
And Read Only Boolean
Then we need an Awake function to enable and handle the Input Actions
If the press or screenPos isn’t working, check the lines carefully if there is a mistake
Then we need the Coroutine Drag that we call when we click the right object and set the isClickedOn to true.
Then when we let go from the game object, we want to check if it’s close enough to the transform position. And if it is, we snap the game object to that position.
Bonus:
There are two ways to use Input Actions and here is the second example where you don’t need to create Input Action Asset.
Changes to the previous script is:
- Namespace: → using UnityEngine.InputSystem;
- Variables: → InputActions press and screenPos
- Awake: → Enable InputActions & change the performer & canceled lines
This way is good for testing and for one or two object(s). Because you have to set the Action Type/Control Type and bindings manually to each object.