Avoid multiple collisions

Hello everyone,

I know there are a lot of threads on this issue, but I haven’t been able to find the solution yet.

In my tennis game, the player hits the ball through the stroke animation (backhand, forehand). The problem is, most of the time the racquet hits the ball just once (as it should be) but every once in a while it hits it two, four and even as many as eight times at once (I know all this because I added a collision counter to debug).

My theory is, the racquet is hitting the ball always at a different angle, depending on how early or late I trigger the animation. Maybe the reason is different, I don’t know.

Whatever the reason is, I can’t find the way to fix it.

What can I do about it? :eyes:

I would put a small timer into your code so that a collision isnt dealt with if one occurred in a short time previous…

ie

float delay = 0;

void OnCollisionEnter(Collision col)
{
  if(delay > 0)
      return;

  delay = 0.5f;

  //handle hitting ball or whatever
}

void Update()
{
if(delay > 0)
    delay -= Time.deltaTime;
}

alternatively, you could setup the ball so it knows who is allowed to hit it. Set its tag or something on hit

Thank you!

I finally solved the problem by making turning isTrigger on and off. I’m not sure how good of an idea that is or how expensive, but it works.

You can solved the problem by using a boolean variable to check if game object is collisonEnter.