Unity’s New Input System: Press and Hold Interaction
Today, I will be going over how to make a ball charge a bounce using a hold interaction!
Prepping the Scene
- Make a floor
- Make a sphere
- Give the sphere a rigidbody component
- Create a Player C# script and assign it to the sphere
- Add a new Input Actions asset
Setting up your Input Action Map
- Create a Player Action Map.
- A jump or bounce action with a button action type.
- Add a binding with a path to the Space key.
- Add a new Hold Interaction and set the Hold Time to 1 second.
- Generate the C# Class
Making the C# Script
First, grab the references to your input and rigidbody from the sphere. Then enable the action map and we need to get access to the information when the action Bouncing is either performed or canceled.
When you hold the space key for the whole duration, the sphere will be launched up at full charge(_bounce).
During a hold interaction, there is a timer that starts as soon as you hit the desired key. You can get that timer’s value if you use obj.duration. That means you can use that value kind of like a “percent of charge” by multiplying it to _bounce. Thus, making a smaller bounce if you release before full charge!
That was how to add a charging action!
Next up, I’ll go over how the new input system helps with rapid prototyping!
See you next time!