How can I remove object by raycast?
Scene raycast
Having recently answered https://blender.stackexchange.com/a/192827/15543 it appears this is another good contender for scene raycast.
Given two global points in the scene raycast from one in direction of other as far as the distance between them Repeat until there are no more obstacles to hit.
import bpy
from bpy import context

from mathutils import Vector

a = Vector((-5, 0, 0))
b = Vector((5, 0, 0))

scene = context.scene

hit, loc, norm, idx, ob, M = scene.ray_cast(
        context.view_layer,
        a,
        (b - a),
        distance=(b - a).length,
        )
if hit:
    print(f&quot;Hit, removing {ob.name}&quot;)
    bpy.data.objects.remove(ob)