You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Three.js Fiber网格交互与react-postprocessing镜头畸变Shader问题

问题:径向畸变后网格点击事件异常

我刚接触Three.js和WebGL,做了个包含多个可交互网格的2D平面场景,用户可以调整相机角度并点击网格进行交互。给整个场景应用径向相机畸变(枕形畸变)后,出现了网格点击事件异常的问题:只有点击网格在场景中的原始(未畸变)位置时,才会触发其点击监听器。

感谢您的帮助,任何建议都将不胜感激。

我使用ycw提供的镜头畸变通道(lens distortion pass),为react-postprocessing创建了自定义效果,相关代码如下:

export interface PincussionDistortionProps {
  distortion: Vector2;
  principalPoint: Vector2;
  focalLength: Vector2;
  skew: number;
}

const LensDistortionEffect = forwardRef<PincussionDistortionProps, any>(
  ({ distortion, principalPoint, focalLength, skew }, ref) => {
    const { camera, scene } = useThree();

    const effect = useMemo(() => {
      return new LensDistortionPass(scene, camera, {
        distortion,
        principalPoint,
        focalLength,
        skew,
      });
    }, [scene, camera, distortion, principalPoint, focalLength, skew]);

    return <primitive ref={ref} object={effect} />;
  }
);

片元着色器(Fragment Shader)

uniform sampler2D tDiffuse;
uniform vec2 uK0;
uniform vec2 uCc;
uniform vec2 uFc;
uniform float uAlpha_c;
varying vec2 vUv;

void main() {
    vec2 Xn = 2. * ( vUv.st - .5 ); // -1..1
    vec3 Xd = vec3(( 1. + uK0 * dot( Xn, Xn ) ) * Xn, 1.); // distorted
    mat3 KK = mat3(
    vec3(uFc.x, 0., 0.),
    vec3(uAlpha_c * uFc.x, uFc.y, 0.),
    vec3(uCc.x, uCc.y, 1.)
    );
    vec2 Xp = ( KK * Xd ).xy * .5 + .5; // projected; into 0..1
    if ( Xp.x >= 0. && Xp.x <= 1. && Xp.y >= 0. && Xp.y <= 1. ) {
        gl_FragColor = texture2D( tDiffuse, Xp );
    }
}

顶点着色器(Vertex Shader)

varying vec2 vUv;

void main() {
    vUv = uv;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

内容的提问来源于stack exchange,提问作者Kn3cht

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:05:35