Why don't you use the Map function to Map the distance of the object to the speed of the motor toward the object so the further away it is from the object the more it drives toward it and the closer it gets the slower it goes. Use an IF or a CASE to change direction if the object gets to close and flags to keep track of whether the object is approaching or receding. The decision code for direction can use these flags to set direction.