RigidBody2D freeze X position

N0xus picture N0xus · Mar 22, 2014 · Viewed 7.3k times · Source

I'm wondering if there is a way to emulate the following line of code using Unity's RigidBody2D as opposed to using a normal RigidBody.

rigidbody.constraints = RigidbodyConstraints.FreezePositionX;

I wanting my players x position to freeze when it collides with something. Whilst I could use the above, it would require I rework all my 2D collisions to work with the 3D collision. A pain I'd rather avoid.

Answer

Bart picture Bart · Mar 22, 2014

This is due to the Box2D engine use to do the simulation. It does not directly provide a constraint on the rigid body itself. It does however provide joints.

What you want to look into is a Slider Joint 2D. This will allow you to constrain movement in a particular direction.

By default it will freeze/constrain the X position (i.e. you can just move up or down). By modifying the angle, you can change the line along which the object is allowed to move.

So let's say you want to constrain movement vertically. In that case, you add a slider joint that looks like this:

This will allow the specific 2D Rigid Body to only move up or down. There are a couple of things to note here. Joints work in relation to other rigid bodies, which you would normally add to the "Connected Rigid Body". If you don't, it will implicitly set up one at the origin (0,0). This will have the effect of snapping your constrained body there, when you might not expect it. This can be modified by changing the "Connected Anchor" settings appropriately.

If you wish to constrain your rigid body horizontally you'd do the same as before, with the addition of an angle. Setting it to 90 degrees will do the trick.

How this fits into your specific setup and code you'd have to try and figure out. But to help you along I've created a small demo scene at over on Github.

It won't do much, but by interacting with the two squares in the scene view (try translating them along an axis) you get the idea what it's doing.