- Home /
How would you code a collectible object so that the actual act of picking up the object takes a certain amount of time?
I already have functionality to pick up collectible objects using collision detection and a simple press of the e key. I was, however, hoping to make it take a set amount of time, say 3 seconds, of pressing the e key within range of the object before pick up occurred. How would I go about doing this? Thank you!
Answer by TanselAltinel · May 15, 2018 at 09:37 PM
There could be multiple solutions to this, but I'd do something like following:
If the player is in close proximity, I'd decide that by using a sphere collider set as trigger. If the object is in the trigger area, then I'd check it in Update function:
void Update() {
if (Input.GetKey("e") && isObjectInVicinity) {
pressedTimer += Time.deltaTime;
if( pressedTimer >= 3) {
// pick up object
}
} else {
pressedTimer = 0f;
}
}
void OnTriggerEnter(Collider other) {
if(other.gameObject.name == "my pick up object") {
isObjectInVicinity = true;
}
}
Of course you could go about different things, like using Vector3.Distance
function to check is object is near, or use CompareTag("object tag")
function in OnTriggerEnter to check if object is pickable.
You can also set object reference to your pickable object.
There are many other ways to do this, I hope my examples give you an idea.
Thank you very much! Your answer helped very much. I'm currently at work and was thinking about this problem, but couldn't test any of my ideas until I got home, which prompted my question to begin with. Some of the ideas I had were along the same lines, but were overly complex when compared to this solution. Thank you again!
I'll give it a shot when I get home and let you know how it turns out. =)
Alright, I hope these help. If not, let me know and we can work on another solution.
It worked great! Thank you so much!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can i rotate my character smooth using keys ? 0 Answers
How can i check and fire an event when the user look at specific object ? 0 Answers
Sorting a list based of a variable 1 Answer