Raycaster.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author bhouston / http://exocortex.com/
  4. * @author stephomi / http://stephaneginier.com/
  5. */
  6. ( function ( THREE ) {
  7. THREE.Raycaster = function ( origin, direction, near, far ) {
  8. this.ray = new THREE.Ray( origin, direction );
  9. // direction is assumed to be normalized (for accurate distance calculations)
  10. this.near = near || 0;
  11. this.far = far || Infinity;
  12. this.params = {
  13. Sprite: {},
  14. Mesh: {},
  15. PointCloud: { threshold: 1 },
  16. LOD: {},
  17. Line: {}
  18. };
  19. };
  20. var descSort = function ( a, b ) {
  21. return a.distance - b.distance;
  22. };
  23. var intersectObject = function ( object, raycaster, intersects, recursive ) {
  24. if ( object.visible === false ) return;
  25. object.raycast( raycaster, intersects );
  26. if ( recursive === true ) {
  27. var children = object.children;
  28. for ( var i = 0, l = children.length; i < l; i ++ ) {
  29. intersectObject( children[ i ], raycaster, intersects, true );
  30. }
  31. }
  32. };
  33. //
  34. THREE.Raycaster.prototype = {
  35. constructor: THREE.Raycaster,
  36. linePrecision: 1,
  37. set: function ( origin, direction ) {
  38. // direction is assumed to be normalized (for accurate distance calculations)
  39. this.ray.set( origin, direction );
  40. },
  41. setFromCamera: function ( coords, camera ) {
  42. if ( camera instanceof THREE.PerspectiveCamera ) {
  43. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  44. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  45. } else if ( camera instanceof THREE.OrthographicCamera ) {
  46. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  47. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  48. } else {
  49. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  50. }
  51. },
  52. intersectObject: function ( object, recursive ) {
  53. var intersects = [];
  54. intersectObject( object, this, intersects, recursive );
  55. intersects.sort( descSort );
  56. return intersects;
  57. },
  58. intersectObjects: function ( objects, recursive ) {
  59. var intersects = [];
  60. if ( Array.isArray( objects ) === false ) {
  61. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  62. return intersects;
  63. }
  64. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  65. intersectObject( objects[ i ], this, intersects, recursive );
  66. }
  67. intersects.sort( descSort );
  68. return intersects;
  69. }
  70. };
  71. }( THREE ) );