- Home /
How can I make it so that inputs only function once per second?
I am trying to get a collision method to work where when the player is holding the chopping key (space) and is colliding with a tree it will increase the hit counter for the tree every second and after the tree is chopped will add score. However my problem is that when I old the space bar there are far too many inputs. So what I've been racking my brain for is some way to only allow the if statement in the collision method to run once per second. I tried a timestamp but it would only increase the chopping counter once, then you would have to recollide with the object. I am using GetKey for the input, and OnCollisionStay2D for the collision.
Thanks.
Answer by chubshobe · Jun 01, 2021 at 09:35 PM
For a custom behavior like this, reading directly from Unity's Input class won't work. Creating a custom intermediate behavior would give you the freedom you're looking for. For example, a custom input class which updates every second.
Thanks, I'll look into that. Currently as is the chopping isn't terrible, but when holding down the space bar the chop counter for the tree only increases once, and you need to recollide with it to increase it again.
Answer by Statement · Jun 02, 2021 at 12:50 AM
Add a trigger around the tree. I was making an example (see here) and I figured that could happen as the character bounces off the tree. Changing to an OnTriggerStay2D likely makes it smoother. So your tree prefab should have two colliders. One that stops the player walking through it, and a bigger trigger collider for chopping purposes.
Ohh, that sounds like it could work, I'll definitely try to work a trigger into it.
Thanks.
Alternatively you might also be able to add a trigger on the player to have as it's "tool zone" or whatever.
Your answer
Follow this Question
Related Questions
2D Platformer - Action When Key Is Pressed During Collision C# 0 Answers
Light Colision 1 Answer
Stop Watch start when told 2 Answers
Animation Curve Data Recording 0 Answers
Time release Collectable 1 Answer