three#Raycaster TypeScript Examples

The following examples show how to use three#Raycaster. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useRaycaster.ts    From trois with MIT License 6 votes vote down vote up
export default function useRaycaster(options: RaycasterConfigInterface): RaycasterInterface {
  const {
    camera,
    resetPosition = new Vector3(0, 0, 0),
  } = options

  const raycaster = new Raycaster()
  const position = resetPosition.clone()
  const plane = new Plane(new Vector3(0, 0, 1), 0)

  const updatePosition = (coords: Vector2) => {
    raycaster.setFromCamera(coords, camera)
    camera.getWorldDirection(plane.normal)
    raycaster.ray.intersectPlane(plane, position)
  }

  const intersect = (coords: Vector2, objects: Object3D[], recursive = false) => {
    raycaster.setFromCamera(coords, camera)
    return raycaster.intersectObjects(objects, recursive)
  }

  return {
    position,
    updatePosition,
    intersect,
  }
}
Example #2
Source File: MapSphereNode.ts    From geo-three with MIT License 6 votes vote down vote up
/**
	 * Overrides normal raycasting, to avoid raycasting when isMesh is set to false.
	 */
	public raycast(raycaster: Raycaster, intersects: Intersection[]): void
	{
		if (this.isMesh === true) 
		{
			return super.raycast(raycaster, intersects);
		}
		
		// @ts-ignore
		return false;
	}
Example #3
Source File: MapPlaneNode.ts    From geo-three with MIT License 6 votes vote down vote up
/**
	 * Overrides normal raycasting, to avoid raycasting when isMesh is set to false.
	 */
	public raycast(raycaster: Raycaster, intersects: Intersection[]): void
	{
		if (this.isMesh === true) 
		{
			return super.raycast(raycaster, intersects);
		}
		
		// @ts-ignore
		return false;
	}
Example #4
Source File: MapHeightNodeShader.ts    From geo-three with MIT License 6 votes vote down vote up
/**
	 * Overrides normal raycasting, to avoid raycasting when isMesh is set to false.
	 *
	 * Switches the geometry for a simpler one for faster raycasting.
	 */
	public raycast(raycaster: Raycaster, intersects: Intersection[]): void
	{
		if (this.isMesh === true) 
		{
			this.geometry = MapPlaneNode.geometry;

			const result = super.raycast(raycaster, intersects);

			this.geometry = MapHeightNodeShader.geometry;

			return result;
		}
		
		// @ts-ignore
		return false;
	}
Example #5
Source File: MapHeightNode.ts    From geo-three with MIT License 6 votes vote down vote up
/**
	 * Overrides normal raycasting, to avoid raycasting when isMesh is set to false.
	 */
	public raycast(raycaster: Raycaster, intersects: Intersection[]): void
	{
		if (this.isMesh === true) 
		{
			return super.raycast(raycaster, intersects);
		}

		// @ts-ignore
		return false;
	}
Example #6
Source File: UseCannon.tsx    From react-ecs with MIT License 6 votes vote down vote up
MouseSystem = () => {
    const query = useQuery((e) => e.hasAll(PhysicsApi, ThreeView));
    const { gl, scene, camera, mouse } = useThree();
    const intersectPoint = new Vector3();
    const raycaster = useRef(new Raycaster());
    const isMouseDown = useRef(false);

    useEffect(() => {
        const onMouseDown = (/*event: MouseEvent*/) => {
            isMouseDown.current = true;
        };
        const onMouseUp = (/*event: MouseEvent*/) => {
            isMouseDown.current = false;
        };
        gl.domElement.addEventListener('pointerdown', onMouseDown);
        gl.domElement.addEventListener('pointerup', onMouseUp);
        return () => {
            // unsubscribe event
            gl.domElement.removeEventListener('pointerdown', onMouseDown);
            gl.domElement.removeEventListener('pointerup', onMouseUp);
        };
    }, [gl.domElement]);

    return useSystem((dt) => {
        raycaster.current.setFromCamera(mouse, camera);
        query.loop([ThreeView, PhysicsApi], (e, [view, physics]) => {
            const intersects = raycaster.current.intersectObject(view.object3d);
            if (intersects.length !== 0) {
                physics.api.applyForce([0, 20, 0], [0, 0, 0]);
            }
        });
    });
}
Example #7
Source File: MapPlaneNode.d.ts    From geo-three with MIT License 5 votes vote down vote up
raycast(raycaster: Raycaster, intersects: Intersection[]): void;
Example #8
Source File: LODRaycast.ts    From geo-three with MIT License 5 votes vote down vote up
/**
	 * Raycaster object used to cast rays into the world and check for hits.
	 */
	public raycaster: Raycaster = new Raycaster();
Example #9
Source File: MapView.ts    From geo-three with MIT License 5 votes vote down vote up
public raycast(raycaster: Raycaster, intersects: any[]): boolean
	{
		return false;
	}
Example #10
Source File: MapSphereNode.d.ts    From geo-three with MIT License 5 votes vote down vote up
raycast(raycaster: Raycaster, intersects: Intersection[]): void;
Example #11
Source File: MapHeightNodeShader.d.ts    From geo-three with MIT License 5 votes vote down vote up
raycast(raycaster: Raycaster, intersects: Intersection[]): void;
Example #12
Source File: MapHeightNode.d.ts    From geo-three with MIT License 5 votes vote down vote up
raycast(raycaster: Raycaster, intersects: Intersection[]): void;
Example #13
Source File: LODRaycast.d.ts    From geo-three with MIT License 5 votes vote down vote up
raycaster: Raycaster;
Example #14
Source File: MapView.d.ts    From geo-three with MIT License 5 votes vote down vote up
raycast(raycaster: Raycaster, intersects: any[]): boolean;
Example #15
Source File: index.ts    From THREE.Interactive with MIT License 5 votes vote down vote up
raycaster: THREE.Raycaster;
Example #16
Source File: index.ts    From THREE.Interactive with MIT License 5 votes vote down vote up
constructor(
    renderer: THREE.Renderer,
    camera: THREE.Camera,
    domElement: HTMLElement,
    dontBindEventsOnBody: boolean | undefined
  ) {
    this.renderer = renderer;
    this.camera = camera;
    this.domElement = domElement;
    this.bindEventsOnBodyElement = true;
    if (typeof dontBindEventsOnBody !== 'undefined' && dontBindEventsOnBody) {
      this.bindEventsOnBodyElement = false;
    }

    this.mouse = new Vector2(-1, 1); // top left default position

    this.supportsPointerEvents = !!window.PointerEvent;

    this.interactiveObjects = [];
    this.closestObject = null;

    this.raycaster = new Raycaster();

    domElement.addEventListener('click', this.onMouseClick);

    if (this.supportsPointerEvents) {
      if (this.bindEventsOnBodyElement) {
        domElement.ownerDocument.addEventListener(
          'pointermove',
          this.onDocumentMouseMove
        );
      } else {
        domElement.addEventListener('pointermove', this.onDocumentMouseMove);
      }
      domElement.addEventListener('pointerdown', this.onMouseDown);
      domElement.addEventListener('pointerup', this.onMouseUp);
    } else {
      if (this.bindEventsOnBodyElement) {
        domElement.ownerDocument.addEventListener(
          'mousemove',
          this.onDocumentMouseMove
        );
      } else {
        domElement.addEventListener('mousemove', this.onDocumentMouseMove);
      }
      domElement.addEventListener('mousedown', this.onMouseDown);
      domElement.addEventListener('mouseup', this.onMouseUp);
      domElement.addEventListener('touchstart', this.onTouchStart, {
        passive: true,
      });
      domElement.addEventListener('touchmove', this.onTouchMove, {
        passive: true,
      });
      domElement.addEventListener('touchend', this.onTouchEnd, {
        passive: true,
      });
    }

    this.treatTouchEventsAsMouseEvents = true;
  }
Example #17
Source File: Player.tsx    From spacesvr with MIT License 4 votes vote down vote up
/**
 * Player represents a physics-enabled player in the environment, complete with a
 * control scheme and a physical representation that interacts with other physics-
 * enabled objects.
 *
 * There should only be one player per environment.
 *
 * @constructor
 */
export default function Player(
  props: { children: ReactNode[] | ReactNode } & PlayerProps
) {
  const { children, pos = [0, 1, 0], rot = 0, speed = SPEED, controls } = props;

  const camera = useThree((state) => state.camera);
  const gl = useThree((state) => state.gl);
  const defaultRaycaster = useThree((state) => state.raycaster);

  const { device } = useEnvironment();

  // physical body
  const [bodyRef, bodyApi] = useCapsuleCollider(pos);
  const { direction, updateVelocity } = useSpringVelocity(bodyApi, speed);

  // local state
  const position = useRef(new Vector3());
  const velocity = useRef(new Vector3());
  const lockControls = useRef(false);
  const raycaster = useMemo(
    () => new Raycaster(new Vector3(), new Vector3(), 0, 1.5),
    []
  );
  const { connected, frequency, sendEvent } = useSimulation();
  const simulationLimiter = useLimiter(frequency);

  // setup player
  useEffect(() => {
    // store position and velocity
    bodyApi.position.subscribe((p) => position.current.fromArray(p));
    bodyApi.velocity.subscribe((v) => velocity.current.fromArray(v));

    // rotation happens before position move
    camera.rotation.setFromQuaternion(
      new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), rot)
    );
  }, []);

  useFrame(({ clock }) => {
    const cam: Camera = device.xr ? gl.xr.getCamera(camera) : camera;

    // update raycaster
    if (device.desktop) {
      raycaster.ray.origin.copy(position.current);
      const lookAt = new Vector3(0, 0, -1);
      lookAt.applyQuaternion(cam.quaternion);
      raycaster.ray.direction.copy(lookAt);
    }

    // update camera position
    camera.position.copy(position.current);

    // update velocity
    if (!lockControls.current) {
      updateVelocity(cam, velocity.current);
    }

    // p2p stream position and rotation
    if (connected && simulationLimiter.isReady(clock)) {
      sendEvent(
        "player",
        JSON.stringify({
          position: camera.position
            .toArray()
            .map((p) => parseFloat(p.toPrecision(3))),
          rotation: camera.rotation
            .toArray()
            .slice(0, 3)
            .map((r) => parseFloat(r.toPrecision(3))),
        })
      );
    }
  });

  const state = createPlayerState(
    bodyApi,
    position,
    velocity,
    lockControls,
    device.mobile ? defaultRaycaster : raycaster
  );

  return (
    <PlayerContext.Provider value={state}>
      {device.mobile && (
        <>
          {controls?.disableGyro ? (
            <TouchFPSCamera />
          ) : (
            <GyroControls fallback={<TouchFPSCamera />} />
          )}
          <NippleMovement direction={direction} />
        </>
      )}
      {device.desktop && (
        <>
          <KeyboardMovement direction={direction} />
          <PointerLockControls />
        </>
      )}
      {device.xr && (
        <>
          <VRControllerMovement position={position} direction={direction} />
        </>
      )}
      <group name="player" ref={bodyRef}>
        {SHOW_PLAYER_HITBOX && <VisibleCapsuleCollider />}
      </group>
      {children}
    </PlayerContext.Provider>
  );
}