setFromCamera method

void setFromCamera(
  1. Vector2 coords,
  2. Camera camera
)

coords — 2D coordinates of the mouse, in normalized device coordinates (NDC)---X and Y components should be between -1 and 1.

camera — camera from which the ray should originate

Updates the ray with a new origin and direction.

Implementation

void setFromCamera(Vector2 coords, Camera camera) {
  if (camera is PerspectiveCamera) {
    ray.origin.setFromMatrixPosition(camera.matrixWorld);
    ray.direction.setValues(coords.x, coords.y, 0.5);
    ray.direction.unproject(camera);
    ray.direction.sub(ray.origin);
    ray.direction.normalize();
    this.camera = camera;
  }
  else if (camera is OrthographicCamera) {
    ray.origin.setValues(coords.x, coords.y,(camera.near + camera.far) / (camera.near - camera.far));
    ray.origin.unproject(camera); // set origin in plane of camera
    ray.direction.setValues(0, 0, -1);
    ray.direction.transformDirection(camera.matrixWorld);
    this.camera = camera;
  }
  else {
    console.error('Raycaster: Unsupported camera type: ${camera.type}');
  }
}