Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export class MouseInput {
- mouse: THREE.Vector2 // carries current position information to the mouse object
- raycaster: THREE.Raycaster
- camera: THREE.Camera
- observables: THREE.Object3D[]
- renderer: THREE.Renderer
- latestIntersectedPoint: THREE.Vector3
- latestIntersectedObject: THREE.Object3D
- tooltip: Tooltip
- constructor(renderer: THREE.Renderer, camera: THREE.Camera){
- this.mouse = new THREE.Vector2()
- this.raycaster = new THREE.Raycaster()
- this.renderer = renderer
- this.camera = camera
- this.observables = []
- this.tooltip = new Tooltip(renderer, camera)
- window.addEventListener('mousemove', this.onMouseMove, false);
- }
- onMouseMove = (event: MouseEvent) => {
- this.mouse.x = ((event.clientX - this.renderer.domElement.offsetLeft + 0.5) / window.innerWidth) * 2 - 1;
- this.mouse.y = -((event.clientY - this.renderer.domElement.offsetTop + 0.5) / window.innerHeight) * 2 + 1;
- }
- observe(object: THREE.Object3D) {
- this.observables.push(object)
- }
- // we calculate intersection during the frame loop
- // after any objects and the mouse have moved around, and right before render probably
- currentIntersection(): THREE.Intersection | null {
- this.raycaster.setFromCamera(this.mouse, this.camera);
- const intersected = this.raycaster.intersectObjects(this.observables)[0];
- if (intersected) {
- const tooltipContents = intersected.object.userData.tooltipContents
- if (tooltipContents) {
- this.tooltip.show(tooltipContents, intersected.point)
- } else {
- this.tooltip.hide()
- }
- return intersected
- } else {
- this.tooltip.hide()
- return null
- }
- }
- }
- export class Tooltip {
- domElement: HTMLElement
- renderer: THREE.Renderer
- position: THREE.Vector3
- camera: THREE.Camera
- constructor(renderer: THREE.Renderer, camera: THREE.Camera){
- this.domElement = document.getElementById('tooltip')!
- this.renderer = renderer
- this.camera = camera
- this.position = new THREE.Vector3
- }
- show(contents: string, point: THREE.Vector3){
- this.domElement.style.display = 'block';
- const canvasHalfWidth = this.renderer.domElement.offsetWidth / 2;
- const canvasHalfHeight = this.renderer.domElement.offsetHeight / 2;
- this.position.copy(point).project(this.camera);
- this.position.x = (this.position.x * canvasHalfWidth) + canvasHalfWidth + this.renderer.domElement.offsetLeft;
- this.position.y = -(this.position.y * canvasHalfHeight) + canvasHalfHeight + this.renderer.domElement.offsetTop;
- const tootipWidth = this.domElement.offsetWidth;
- const tootipHeight = this.domElement.offsetHeight;
- this.domElement.style.left = `${this.position.x - tootipWidth/2}px`
- this.domElement.style.top = `${this.position.y - tootipHeight - 5}px`
- this.domElement.innerHTML = contents
- console.log('show', contents, point)
- }
- hide(){
- this.domElement.style.display = 'none';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement