Switch between two values

I have an object that I wanted to only be limited to two possible locations, ex: X=0 OR X=1… so if the object is on X=0 and I move it forwards, it jumps to X=1, and if X=1 and I move it backwards, it jumps to X=0.

Using the Limit Location constraint only allows me to limit the object location inside a range (if min=0 and max=1, location can be 0.5, 0.3, 0.8 etc).

Is there any way to do it, even if using drivers and python expressions (maybe using an OR logic gate)?


Well, I just managed to do the switch positions thing on the viewport (which is what I wanted), using drivers and a scripted expression (avoiding a dependency cycle which is the worst problem).

The secret was using a driver on Delta Transforms instead of regular transforms, because if you use a driver on the regular transforms (ex: X-Location), Blender doesn’t let you move the object at all on the viewport, but changing Delta values still lets you move the object on the viewport so we can use any local location changes to trigger the driver.

The final driver uses the Local Location of the object (var), and also the Data Path of it’s own Delta Location(var2). The scripted expression is as follows:

1 if (var>0 and var!=0 and var2!=1) else 0 if (var<1 and var!=1) else 1

The logic of the expression is:

The initial Delta Location is Value1 which is X=0

The final Delta Location is Value2 which is X=1

So if the cube Local Location(var) is anything but Value1, which it is as soon as I move it a little bit and it leaves 0, then the cube Delta Location must be changed to Value2, so the cube jumps to X=1.

Since the first IF part of the expression also determines that the Delta Location must not be exactly Value2, and now it is, then the IF becomes invalid and the Else part happens, so when I try to move the cube from X=1 back to zero it then checks if the Local Location is less than Value2 and also not exactly Value2 meaning that it just left X=1. If yes, then the cube’s Delta Location must be changed to Value1, so the cube jumps to X=0, back to the start.

The last Else is unnecessary because it never happens, but I must use it for the expression to be valid.
I also added a limit location constraint to keep the cube inside the 0-1 range.

Here is an image:

And a gif of it working: