将片段着色器threejs中的ndc坐标转换为世界坐标

时间:2018-04-23 12:50:09

标签: three.js glsl webgl fragment-shader

我的目标是在我的鼠标光标上画一个圆圈。

我得到代表我光标位置的NDC坐标(-1到+1):

const rect = targetHTML.getBoundingClientRect();
const mousePositionX = event.clientX - rect.left;
const mousePositionY = event.clientY - rect.top;

this._currentPoint = {
  x: (mousePositionX / targetHTML.clientWidth *  2 - 1),
  y: (mousePositionY / targetHTML.clientHeight *  -2 + 1),
};

我通过制服将其传递给我的片段着色器:

this._cursorMaterial.uniforms.uBrushPosition.value =
  new window.THREE.Vector2(this._currentPoint.x, this._currentPoint.y);

在我的片段着色器中,我想将其转换为世界坐标,以便将其与片段世界位置进行比较。

// vertex shader
varying vec4 vPos;
void main() {
  vPos = modelMatrix * vec4(position, 1.0 );
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 );
}

// fragment shader
varying vec4 vPos;
uniform vec2 uBrushPosition;
void main() {
  // convert uBrush position to world space
  // uBrushPosition
  vec3 brushWorldPosition = ?

  // 
  if (distance(brushWorldPosition, vpos) < 10.) {
    gl_FragColor = vec4(1., 0., 0., .5);
  }
  discard;

1 个答案:

答案 0 :(得分:0)

不在着色器中,但您可以将其作为制服发送。

var mouseWorld = new THREE.Vector3( mouse.x, mouse.y, distanceFromCamera )
mouseWorld.unproject( camera )