- Home /
[2D][Beginner]How do I heal my character when pressing a key while next to a health pack?
I need my character to heal when I press E next to a health pack.
use OnCollisionStay ins$$anonymous$$d of OnCollisionEnter
OnCollisionEnter is only triggered once, so you'll have only 1 frame of time to press E key. While OnCollisionStay is triggered continuously when ur in the trigger.
Answer by unity_qrj_5UYMolP0jA · Jun 07, 2020 at 12:04 AM
Your problem is that you're only checking for E only when the the player enters the collision for the health pack.
What you need is a bool (I.E. playerContact = true), set to true on collision enter and false on collision exit.
Then in update, check for both input of E, and that your bool is set to true. So the health pack script should look something like this;
void Update()
{
if (playerContact == true && Input.GetKeyDown(KeyCode.E))
{
umbrellaBar.currentHealth += refillValue;
{
{
void OnTriggerEnter2D(Collider2D bump)
{
if (bump.name == "Player")
playerContact = true;
}
void OnTriggerExit2D(Collider2D bump)
{
if (bump.name == "Player")
playerContact = false;
}
EDIT: As Shady Productions pointed out there is also the OnCollisionStay function instead of OnCollisionEnter. https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionStay.html
void OnCollisionStay(Collision collisionInfo)
{
if(bump.name == "Player" && Input.GetKeyDown(KeyCode.E))
{
umbrellaBar.currentHealth += refillValue;
}
}
One thing to point out, is that with both solutions however, is a potential bug. If you have AI enemies walking around and they enter the health packs collision, you're not checking it's the actual player you've bumped into, and it's just checking for all collisions. So if an enemy walks into the collision and the player presses E while being far away from the health pack, it will still execute the refill health code. To avoid this, check the collision is with the player using Bump. I've added it to the above code. If your Player game object is named Player, it'll work. Otherwise change "Player" to whatever name the player game object is using.
Or that... To be honest, I did think of that after after I posted :/ It's just more of a personal preference of $$anonymous$$e to keep that kind of functionality in Update() so it's easy to find when scripts start getting a bit longer.... But OnCollisionStay would be less overhead.
Your answer
Follow this Question
Related Questions
Health subtracts when hit by bullit 2 Answers
Drag and release 2 Answers
Enemy Health Bar UI 1 Answer
Scaling related to damage 2 Answers