Hello.
I am new to Unity and my first project is supposed to be some kind of a 3D Pong Prototype game for the IPhone. Thanks to the great documentation and the tutorials, I didn’t encounter that many problems yet.
Anyway, here is my setup, followed by my question:
There is a sphere = ball in a room and two rackets/bats.
To let the ball fly and bounce around in the room i am using two functions: FixedUpdate and OnCollisionEnter.
private var epsilon : float = 0.01;
function FixedUpdate() {
if(isServed) {
newPosition = direction.normalized;
newPosition *= speed;
newPosition *= Time.deltaTime;
transform.Translate(newPosition);
//...
}
}
function OnCollisionEnter(collision : Collision) {
Debug.Log("Amount of collisions: " + collision.contacts.length);
// for(var i : int = 0; i < collision.contacts.length; i++) {
var contact = collision.contacts[0];
//...
var normalOfObject = contact.normal;
direction.x *= Mathf.Abs(Mathf.Abs(normalOfObject.x) - 1.0) < epsilon ? -1 : 1;
direction.y *= Mathf.Abs(Mathf.Abs(normalOfObject.y) - 1.0) < epsilon ? -1 : 1;
direction.z *= Mathf.Abs(Mathf.Abs(normalOfObject.z) - 1.0) < epsilon ? -1 : 1;
// }
}
The ball itself has a sphere collider and a rigidbody attached(gravity is off, freeze rotation is on) (none of the other objects have rigidbody attached). The room is a rectangular tube (is that proper english?): A 3dObject imported from a 3ds max project and uses that mesh as its mesh collider. The two rackets/bats, that play the ball are rotated planes and use the plane as collider. This all works well, mostly.
But sometimes instead of bouncing off the wall, the ball sticks on the wall and stops moving completely. Or sometimes it stays in the corner and only moves along the z axis.
Is this bounce calculation somehow wrong? Mathf.Abs cannot take that long to calculate and produce this error, or am i wrong?
Also the ball sometimes just flies through the planes/rackets/bats, but i am guessing that this problem occurs because of the speed of the ball, since it happens far more often, whenever i set the speed to a high value (collision is not recognized?!). How could i get rid of that? Use a box instead of a plane?
Thanks for any help in advance!
(Oh how i love these “sometimes-happen-bugs”…)