Ray.intersectsSphere giving incorrect intersection results

I have a seen where I’m trying to show direct line of sight. Using
ray.intersectsSphere(sphere) I’m getting definite intersections as show below.

Screen Shot 2021-02-19 at 10.58.10 AM|639x500

However with a custom function


function lineSphereIntersection(start: Vector3, end: Vector3, sphere: Sphere): Vector3[] {
  const { x: cx, y: cy, z: cz } = sphere.center
  const { x: sx, y: sy, z: sz } = start
  const { x: ex, y: ey, z: ez } = end
  const v = end.clone().sub(start)
  const r = sphere.radius
  const a = v.lengthSq()
  const b = 2 * (sx * v.x + sy * v.y + sz * v.z - v.x * cx - v.y * cy - v.z * cz)
  const c = sx * sx - 2 * sx * cx + cx * cx + sy * sy - 2 * sy * cy + cy * cy + sz * sz - 2 * sz * cz + cz * cz - r * r
  const d = b * b - 4 * a * c

  if (d < 0) return []

  const t1 = (-b - sqrt(d)) / (2 * a)

  const solution1 = new Vector3(
    sx * (1 - t1) + t1 * ex,
    sy * (1 - t1) + t1 * ey,
    sz * (1 - t1) + t1 * ez,
  )

  if (d === 0) return [solution1]

  const t2 = (-b + sqrt(d)) / (2 * a)
  const solution2 = new Vector3(
    sx * (1 - t2) + t2 * ex,
    sy * (1 - t2) + t2 * ey,
    sz * (1 - t2) + t2 * ez,
  )

  if ((t1 > 1 || t1 < 0) && (t2 > 1 || t2 < 0))
    return [];
  else if (!(t1 > 1 || t1 < 0) && (t2 > 1 || t2 < 0))
    return [solution1]
  else if ((t1 > 1 || t1 < 0) && !(t2 > 1 || t2 < 0))
    return [solution2]
  else
    return [solution1, solution2]
}

I get the correct behavior.
Screen Shot 2021-02-19 at 10.56.14 AM|639x500

My guess since this hasn’t been brought up I’m missing some setup of the Ray/Sphere interaction. I made sure to normalize the direction. Is there a bug in the ray/sphere or am I misusing it?

Please modify the following live example to demonstrate the issue: https://jsfiddle.net/1uLdbm72/

User error. I was copying the target into the ray direction, instead of (origin-target).normalize(). Doing that fixed it. Thanks @Mugen87

1 Like