ProximityController.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * ProximityController.js
  3. *
  4. * @author realor
  5. */
  6. import { Controller } from './Controller.js'
  7. import * as THREE from '../lib/three.module.js'
  8. class ProximityController extends Controller {
  9. constructor(object, name) {
  10. super(object, name)
  11. this.distance = 3
  12. this.output = 0
  13. this.objectsGroup = ''
  14. this._onNodeChanged = this.onNodeChanged.bind(this)
  15. this._objects = null
  16. this._vector1 = new THREE.Vector3()
  17. this._vector2 = new THREE.Vector3()
  18. }
  19. onStart() {
  20. const application = this.application
  21. if (this.objectsGroup && this.objectsGroup.length > 0) {
  22. this._objects = application.scene.getObjectByName(this.objectsGroup)
  23. console.info('OBJECTS:' + this._objects)
  24. }
  25. application.addEventListener('scene', this._onNodeChanged)
  26. }
  27. onStop() {
  28. const application = this.application
  29. application.removeEventListener('scene', this._onNodeChanged)
  30. }
  31. onNodeChanged(event) {
  32. if (event.type === 'nodeChanged') {
  33. if (this._objects) {
  34. for (let object of event.objects) {
  35. if (object.parent === this._objects) {
  36. let range = parseFloat(this.distance || 1)
  37. let value = this.output
  38. let newValue = 0
  39. let children = this._objects.children
  40. let i = 0
  41. while (i < children.length && newValue === 0) {
  42. let child = children[i]
  43. if (this.isNearObject(child, range)) newValue = 1
  44. i++
  45. }
  46. if (newValue !== value) {
  47. this.output = newValue
  48. this.application.notifyObjectsChanged(this.object, this)
  49. }
  50. }
  51. }
  52. } // camera
  53. else {
  54. const camera = this.application.camera
  55. if (event.objects.includes(camera) || event.objects.includes(this.object)) {
  56. let range = parseFloat(this.distance || 1)
  57. let value = this.output
  58. let newValue = this.isNearObject(camera, range) ? 1 : 0
  59. if (newValue !== value) {
  60. this.output = newValue
  61. this.application.notifyObjectsChanged(this.object, this)
  62. }
  63. }
  64. }
  65. }
  66. }
  67. isNearObject(other, range) {
  68. this._vector1.set(0, 0, 0)
  69. other.localToWorld(this._vector1)
  70. this._vector2.set(0, 0, 0)
  71. this.object.localToWorld(this._vector2)
  72. const distance = this._vector1.distanceTo(this._vector2)
  73. return distance < range
  74. }
  75. }
  76. Controller.addClass(ProximityController)
  77. export { ProximityController }