Why does this code make everything fall through the floor.

So I’ve spent the last 4 hours tracking down a weird bug before narrowing it down to a block of code I will past shortly.

The bug was basically that, seemingly at random, every object with a characterController and the standard characterMover script would all at once stop registering collisions and just begin falling through all of my geometry. I was confused when the bug appeared because I could not see how any of my recent code changes would have caused it. Sometime it would manifest right after starting the level, other times it would take longer.

I’ve narrowed it down to the following code

	var startRot = transform.rotation;
	transform.LookAt(target.transform);
	var endRot = transform.rotation;
	
	transform.rotation=Quaternion.RotateTowards(startRot,endRot,turnSpeed*Time.deltaTime);

This code is attached to a gun turret. I want it to slowly rotate towards the player (target). If it matters I am using a cylinder mesh currently parented to a cube until I make the art.

The floor is a plane, but the same thing happens if I make the floor a box or anything else.

I’m not expecting to get a definitive answer, but something that will point me in the right direction of figuring out why this is causing such an odd problem.

I’ve rewritten the code to achieve the same effect another way, but I am hopping I can at least learn something from this.

EDIT: In particular it seems to be the Quaternion.RotateTowards that is giving me the trouble. If I replace it with Slerp, I don’t seem to fall through the floor anymore…

EDIT 2: I should note that the code lives inside the update function and is not inside any loops. It seems to be more likely to trigger the problem if the angle it needs to rotate is very high.

RotateTowards have a problem: sometimes it rotates around the wrong axis (Z instead of Y - don’t know why!). I used a hack found in the FPS Tutorial enemy AI script to fix it:

transform.rotation=Quaternion.RotateTowards(startRot,endRot,turnSpeed*Time.deltaTime);
// force the rotation to be strictly around Y:
transform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);

But I also had the “character falling through the floor problem” once, and apparently it occurred when the framerate dropped to a extremely ridiculous level - under about 4 frames per second. This seems to cause a collision system failure, because several coins I had along the path (triggers) also started to be picked randomly a little before the player fell to eternity.

Check if the problem #1 isn’t causing a severe frame rate drop - if RotateTowards is inside a loop and blocks Unity when rotating, for instance.