I’m making a baseball game where a pitcher throws a ball at a batter, and the batter swings a bat to hit the ball.
The problem is that collisions are happening when the ball is nowhere near the bat.
The batter swing is an animation: it moves a bat that has a capsule collider, radius 0.1 and height 0.35. The ball is a rigid body with a sphere collider, radius of 0.08, interpolation set to extrapolate.
The maximum distance at collision should be about 0.43. And for the most part I get that, averaging about 0.4.
For the first few swings (30 or so) the bat collider behaves correctly, after that I sometimes get collision distance of up to 3.0. Even when I don’t swing.
The bat model stays in it’s place, but the collider seems to be going off on it’s own.
Has anyone else had this problem, and better yet, is there a solution?
I’ve implemented a hack fix for this problem. The ball has an attached script as does the player swinging the bat.
The player controller script calls a method on the ball controller script that tells the ball to ignore collisions when the swing animation is not playing AND the ball is more than 1.0m away from the bat. So if the player swings and the ball is less than a meter away the player script calls a method on the ball script to stop ignoring collisions between it and the bat.
This has reduced the problem a bit, but collisions still occur at distances greater than 1.0m occasionally.
This problem happens on the iPhone where I’m getting 20fps, and the Unity IDE where I’m getting 100fps.
Even after my first hack fix the collisions were still separated by about one meter. While watching the collisions in Unity scene viewer, where I was able pause the game at each frame, I found that disabling the bat and then re-enabling the bat would reset the bat collider and bring the bat/ball collision distance back to reasonable distances.
So I did that in the code as well, when the bat/ball collision distance became greater than 0.4m I would reset the bat and its’ components.
Resetting the bat seems to reset its collider. I find that I need to reset the bat every 30 seconds.
Needless to say, I still don’t know what the real problem could be, and what the real solution is.
Is there a way to induce memory leaks in c#? (I may have forgotten to mention that I’m using the c# scripting, not boo or javascript).
Anyway, thanks in advance for any help.