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.
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.
}
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.