سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

Here is a script component I use in Unity2D to lock the axis on any object. Just attach the script, choose an axis from the dropdown, and you should be good to go. Note your object will need a rigidbody2d and collider to work properly of course.

Thanks to @Bart for a great answer on how Slider Joint 2D works. If this script doesn't make sense see his answer.

using UnityEngine;
using System.Collections;

enum AxisDirection {
    x, y
}

[RequireComponent (typeof (SliderJoint2D))]
public class AxisLock : MonoBehaviour {
    [SerializeField] AxisDirection lockAxis;

    void Awake () {
        SliderJoint2D slider = GetComponent<SliderJoint2D>();

        slider.connectedAnchor = new Vector2(transform.position.x, transform.position.y);
        slider.collideConnected = true;

        if (lockAxis == AxisDirection.x) {
            slider.angle = 90;
        } else {
            slider.angle = 0;
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top