Detecting position change in distance over X axis

Hi, I'm looking for the best suitable sensor for detecting the change the position of an object in horizontal (X) direction. I want to know not only if its moving in this direction but the distance it moves. In my case the distance will be between 1 cm to a meter.
I read about the accelerators, but from what I understand it is not easy to calculate the distance without big error.

Draw a picture showing the hardware setup.

An accelerator pedal makes a car go. An accelerometer is a sensor for measuring acceleration. Yes, they
are not good for distance due to the double-integration leading to lots of drift.

You need to say more about the application before a suitable sensor can be chosen.