Highly recommended fix

Hello, I’m Noah. I’m not Ben, but I have been programming in Unity/C# for a while. I took this course as a refresher, and have found that the system of locking the Z coordinate in rigidbody, and locking the X and Y rotation in rigidbody does not always work. It does its job pretty well, however, it doesn’t actively correct minor changes, it just keeps them. This means that very gradually, the rocket will begin to tilt off course and rotate in the wrong directions. This code fixes this problem all together, without the need for zing anything:

transform.position = new Vector3(transform.position.x, transform.position.y, 0); // freeze the z coordinate at 0
transform.rotation = Quaternion.Euler(0.0f, 0.0f, transform.rotation.eulerAngles.z); // freeze x and y rotation

paste these lines into your rotation method, and you will find that the z coordinate is permanently 0, and that the x and y rotation is permanently 0. best of luck!

4 Likes

Nice solution!

I’d set this in my Start(), and it seems to keep me “on the rails”:

  thisRigidbody.constraints = 
     RigidbodyConstraints.FreezeRotationX | 
     RigidbodyConstraints.FreezeRotationY | 
     RigidbodyConstraints.FreezeRotationZ |
     RigidbodyConstraints.FreezePositionZ;

But I think I prefer the way you’ve done it, honestly… thanks!

1 Like

Wow! This is awesome!

Yeah I was frustrated a little bit how the constraints in the rigid body component didn’t quite achieve what we wanted, so SUPER excited this works.

However, it’s kinda cryptic, haha, would you mind taking a second and explaining the how?

How this works is each and every frame you are essentially filtering the values of your transform.position and transform.rotation. You are allowing pos-x, pos-y and rot-z “thru” your filter, and everything you “trap” in your filter is replaced with a zero value. It’s actually quite elegant, and a perfect programmer’s solution. Well done, Noah!

Ah, now that I look at it it makes sense.
Thanks Jack

Privacy & Terms