- Home /
Create an environmental hazard area
Hey everybody. I need a bit of guidance. Basically I need to create an area that if a player stands in, he loses health. I've made a few attempts, but have come up short. I tried using a box collider on an empty gameobject, but it sets up the invisible wall. If I make it a trigger, the gameObj is destroyed. Is there an easier way to do it than just set up a bounding area in a script? Does unity have a way to get this effect?
Trigger should work fine. You have to check your code and see why the object gets destroyed immediately - are you dealing damage each frame the object is inside the trigger? If so, make sure it's independent of frame rate with Time.deltaTime
Answer by sparkzbarca · Nov 21, 2012 at 08:24 AM
this is because your instantly draining his health REALLY REALLY fast. your draining every update and update is called maybe 50 maybe hundreds of times a second.
what you need to do is drain health, delay, drain again.
you need something like a drain health function and then use
invokerepeating(drain_health,delay);
REALLY THOUGH what you need is to read this. http://unitygems.com/mistakes1/ expand the make something happen in the future text by clicking on it.
you'll see this like a few paragraphs in.
The example above shows how to create a timer suitable for triggering an action when the player remains inside a zone. For instance if the player enters a fire zone, simply harming the player in the Update would kill him within a second. With the timer we can harm him every x seconds.
or EXACTLY WHAT YOUR DOING. :)
you'll also see it followed up with.
Still, Unity offers better solutions as shown in the next part.
so you'll probably want to read up on that next part. :P
It will explain in detail exactly how to solve your issue.
Mark as answered and have a nice day. :)
Ins$$anonymous$$d of InvokeRepeating, you can use Time.deltaTime to control the speed of health decay.
void OnTriggerStay(Collider other)
{
PlayerScript player = other.GetComponent<PlayerScript>();
if (player)
{
player.health -= healthDecaySpeed * Time.deltaTime;
}
}
Actually, the player object isn't being destroyed, its the emptyGame obj with a box collider. The only thing the hazard object has is a box collider, with no mesh. The script only sends out a debug when the OnTriggerEnter() is called. Essentially, as soon as my character triggers the box collider, it kills the empty Gameobject.
Your answer
Follow this Question
Related Questions
Simplistic Colliders for enemies 1 Answer
Avoid Rigidbody Intersection 1 Answer
Inconsistent Collision Detection 3 Answers
physics.OverlapSphere colliders 1 Answer
How do I make a rigidbody bounce off a mesh collider? 0 Answers