How to ignore the transparent part of Sprite by Ray pickup?

How to ignore the transparent part of sprite by Ray pickup?

1 Like

This was not an answer to the question. It links to another question that was also not answered.

In order to ignore the transparent part, look at the object material map image and see if the ray was cast through a transparent part of the image

// For every intersected object returned by the raycaster
let closestIntersect
for ( const intersect of intersectObjects ) {
  const { object } = intersect
  // If the mesh type is sprite
  if ( object.type === `Sprite` ) {
    // Get the image from the intersect object mesh
    const { image } = object.material.map
    // 2D ratio of where the mouse is on the image
    const { uv : { x : UX, y : UY } } = intersect
    // The actual w, h of the image
    const { width : OW, height : OH, src } = image
    // Get the image data, 
    const imageData = getImageData( image )
    // the X & Y of the image
    const x = Math.round( UX * OW )
    const y = OH - Math.round( UY * OH ) // reverse because threejs
    // the index of image data y is every row of pixels, x is on a row of pixels
    const I = ( x + y * OW ) * 4
    // the fourth (3) of every 4 numbers is the alpha value
    const A = imageData.data[ I + 3 ]
    // if A is 0 then it's transparent
    if ( A === 0 ) { continue }
  }
  closestIntersect = intersect; break
}

function getImageData ( image ) {
  const canvas = document.createElement( 'canvas' )
  const context = canvas.getContext( `2d` )
  let { naturalWidth: w, naturalHeight: h } = image
  canvas.width = w
  canvas.height = h
  context.drawImage( image, 0, 0, w, h )
  const imageData = context.getFullImageData()
  return imageData
}
2 Likes