I need my character to heal when I press E next to a health pack.
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.
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.