For every object you want to be hit-able, define a bounding object. Simple examples would be a sphere or a box. Then you have to implement a ray-sphere or ray-box intersection.
For exaple have a look at line-sphere intersection. For boxes, you can either test aginast the four bounding lines, but there are algorithms optimsed for axis aligned boxes.
With this, proceed as you already do. For every object in the scene, check for intersection, if intersects, compare distance to previous intersected objects, take the one that is hit first.
The intersection algorithems give you the ray parameter as a result (the value t for which hit_position = ray_origin + t * ray_direction
) which you can use to compare the distances.