I've got a basic car-based game I'm starting in Unity. Currently the scene has only a floor, a car (player-controlled), and one building.
Bumping into the building at low to medium speeds works as expected. When getting the car up to max speed and smashing into the building, though, weird results happen.
Originally, the car was being pushed through the floor and falling off the map. I changed the floor from a plane to a cube that was stretched to be broad and flat (scale 2 height), and that helped. Now the car seems to clip right through the building at top speed, sometimes flipping itself into the air when it emerges.
So what gives?
The car and building are both imported .fbx models and both have box colliders stretched to the outer bounds of the models. The car has a rigid body with gravity. The building used to have a rigid body, but I removed it once I realized it was making the building fly into the air on impact (which was definitely not what I wanted).
Here are the relevant parts of the movement code:
bool key_up = false;
float top_speed = 1f;
float current_speed = 0f;
float acceleration = .01f;
void Update ()
{
if (Input.GetKeyDown (KeyCode.UpArrow) && !key_up) key_up = true;
if (Input.GetKeyUp (KeyCode.UpArrow) && key_up) key_up = false;
if (key_up)
{
if (current_speed < top_speed) current_speed += acceleration;
}
else
{
if (current_speed > -.1f && current_speed < .1f) current_speed = 0f;
if (current_speed != 0f) current_speed = current_speed * 0.9f;
}
transform.Translate (0f, 0f, current_speed);
}
Update:
After switching the camera to a fixed position (rather than following the car), I've gotten better observations. The car will clip right through at any speed if I keep pushing forward. There's initial resistance from the collision detection and some stuttering from the car, but it always breaks through and then flips into the air on its way out.
I've added the following function to the car code:
void OnCollisionEnter (Collision collision_info)
{
current_speed = 0f;
}
current_speed is what's being used to translate the car forward each frame. This has slowed the bug down, but the car always eventually pushes through if I hold down the gas long enough. It looks as if Unity's collision detection isn't moving the car back far enough on each frame that the car is colliding. Must I handle that portion on my own?