Prevent X Axis movement 2D

Hello,

I have an Object (Spike) which has a rigidbody2D and a collider and I wrote a script to Add force to it to move up and when it reaches a certain point I stop the add force and it falls down, and this goes through a loop, it looks great and the rigidbody makes the movement physics look real.

My problem is if an object hits the spike from the side the spike will move in the x axis and I don’t want that, I want to lock the x Axis movement and allow the Y Axis, how can I do that?

btw I don’t want to remove the Rigidbody and move the object through the code becase I tried it and the movement looks awful.

Have a look at the Rigid Body - under Contraints there’s an option to freeze position and rotation in any of the three axes.

Try locking the z/x position.

One thing you could do is just store the X value upon awakening

float xPos;

void Awake ()
{
    xPos = transform.position.x;
}

Then, every fixed update, just set the x value to the stored value

void FixedUpdate ()
{
    //All your other stuff
    transform.position = new Vector3(xPos, transform.position.y, 0); //For the Z value, if it isn't 0, you can set it to the transform.position.z, or just store another variable if you want.
}

Setting Rigidbody2D.velocity to 0 on each fixed update seems like a viable option.

Why not just use a SliderJoint2D? This is exactly what it’s for. It doesn’t have to be connected TO anything, in which case it will just connect to a fixed point.

HI buddy,

If you need to free a gameobject x movement you can try this:

You should try to modify its X position using a specific number.

You can try to do this:

float x_pos;
void Start()
{
x_pos = transform.position.x;
}

void Update()
{

transform.position = new Vector2(x_pos,transform.position.y);
}

So with this you’re telling that the initial X position that you gameobject have will be forever
the same position making it freeze.

Tell if works.
Greetings.

One way to do this:
Rigidbody2D myBody;

void Awake()
{
myBody=this.GetComponent<Rigidbody2D>();
}

void Update()
{
myBody.velocity = new Vector3(0,myBody.velocity.y);
}