In this article, we’ll explore collision handling and player stats to create health packs which players can walk over to heal themselves.
Creating the Pack
The health pack itself can be a
articles/Mesh Parts|mesh, group of parts (
articles/3D Modeling with Parts|solid-modeled object, or even a simple
Part. Whatever type you choose:
- Anchor the object so players can’t kick it around.
- Insert a
Scriptas a direct child of the object (if you’re using a group of parts, insert the script as a child of the health pack’s “case” since we’ll use it for collision detection).
For a basic health pack, any player that touches it should get healed, so the script needs a
BasePart/Touched|Touched event. In the function that’s triggered by the event, we need to confirm that whatever touched the health pack is a player character (otherwise the health pack will try to heal anything it comes in contact with). To achieve this, we’ll check if the parent object that touched the health pack contains a
Humanoid, a special
Instance that’s part of all player characters.
By default, Roblox characters have 100 health, so let’s create a
healAmount variable set to 30. We can then use the
Humanoid/Health property to add health to the player that touched the pack.
At this point, the
BasePart/Touched|Touched event will continue to fire when any part of the character — foot, hand, leg, etc. — touches the health pack, potentially boosting the player’s health by much more than 30. To fix this, first create a
cooldown variable, representing how many seconds the health pack’s “cooldown” will last, and
canHeal as a boolean for whether the pack can heal:
Now, in the conditional statement that checks for a
Humanoid, test whether
true. If it is, set it to
false so the healing code won’t immediately execute again. After the character is healed, wait for the duration of
cooldown and then set
canHeal back to
The health pack is now functional but a few additions will make it even better.
Max Health Check
The pack shouldn’t heal characters who are already at full health, so let’s add another condition which checks if the player’s health is below the max amount:
A visual indication during the pack’s cooldown period will inform players that it can’t currently be collected. If your health pack is a single mesh or object (not a group of objects), you can simply increase its
BasePart/Transparency|Transparency during the cooldown period and reset it afterwards:
If you don’t want a multi-use health pack — for example, if you want to store the pack in
ServerStorage and clone copies to the game world for one-time usage — just remove all of the cooldown logic and add a
Instance/Destroy|Destroy() command after the healing code: