- Home /
How to Disable a function for a brief period after being activated
Hi I am trying to build a simple game where a player is bouncing on a trampoline type object the problem is if I hit the side of the trampoline it applies the .AddForce multiple times (because of multiple collisions) and sends the player flying out of frame. I was wondering how to disable the .Addforce effect for a short period of time after each bounce. Here is the code I am using.
void OnCollisionStay(Collision collision) {
if (collision.rigidbody)
collision.rigidbody.AddForce (Vector3.up * 300);
}
Thank you!
Answer by Flightkick · Jun 18, 2015 at 04:43 AM
You could add a second collider and configure it like this:
Collider 1: Matches the whole trampoline so players can't walk through it.
Collider 2: (Enable isTrigger) matches the elastic part of the trampoline, if the player hits it then apply force.
EDIT: like ian_sorbello mentions you should also use the OnCollisionEnter() if you want to trigger the event only once.
Answer by ian_sorbello · Jun 18, 2015 at 01:40 AM
You are choosing to run this code within the OnCollisionStay() function - which means it will run every frame that the collision is still in effect.
Rather than "pause" the force addition during this time - just use OnCollisionEnter().
It will only be called once when the collision first occurs - and so you can apply your force once and not think about it again.
And, when in doubt, just put an artificial delay in, anyway. Then, you won't have to worry about multiple triggers in the same frame sending you flying.
public float bounceDelay = 0.125f; // 1/8-second delay between bounces
float lastBounce = -1.0f; // $$anonymous$$eeps track of bounce time
void OnCollisionEnter(Collision collision)
{
if (collision.rigidbody && Time.time > lastBounce + bounceDelay)
{
collision.rigidbody.AddForce(Vector3.up * 300);
lastBounce = Time.time;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Disabling Character movement in C# 3 Answers
Can't use script name as variable type? 2 Answers