AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79596310
Accepted
leon
leon
Asked: 2025-04-28 18:56:11 +0800 CST2025-04-28 18:56:11 +0800 CST 2025-04-28 18:56:11 +0800 CST

在 React Three Fiber 中使用 CameraControls 时如何实现视图偏移平移?

  • 772

在 camera-controls 源代码中,有一个视图偏移的示例。如何使用包装在“@react-three/drei”中的 CameraControls 来实现这个功能?

let offsetUpdated = false;
const viewOffset = new THREE.Vector2();
const cameraControls = new CameraControls( camera, renderer.domElement );
cameraControls._truckInternal = ( deltaX, deltaY ) => {

    viewOffset.x += deltaX;
    viewOffset.y += deltaY;

    camera.setViewOffset(
        width,
        height,
        viewOffset.x,
        viewOffset.y,
        width,
        height,
    );
    camera.updateProjectionMatrix();
    offsetUpdated = true;

}

示例来源:查看代码

现场演示:查看演示

更新:

@Łukasz-daniel-mastalerz 非常感谢!你的代码可以运行,但是有一个奇怪的着色问题MeshReflectorMaterial。我复制了你的代码,并添加了更多对象:我的场景演示

平移后出现奇怪的阴影: 阴影问题

three.js
  • 1 1 个回答
  • 52 Views

1 个回答

  • Voted
  1. Best Answer
    Łukasz Daniel Mastalerz
    2025-04-28T21:48:54+08:002025-04-28T21:48:54+08:00

    如果我理解正确的话,您想要将逻辑从 vanilla 重写为Drei ...offset

    import React, { useRef, useEffect } from "react";
    import { Canvas, useFrame, useThree } from "@react-three/fiber";
    import { CameraControls } from "@react-three/drei";
    import * as THREE from "three";
    import "./styles.css";
    
    function OffSet() {
      const controls = useRef(null);
      const viewOffset = useRef(new THREE.Vector2(0, 0));
      const { camera, size } = useThree();
    
      useEffect(() => {
        if (!controls.current) return;
        const cc = controls.current;
    
        cc._truckInternal = (deltaX, deltaY) => {
          viewOffset.current.x += deltaX;
          viewOffset.current.y += deltaY;
    
          camera.setViewOffset(
            size.width,
            size.height,
            viewOffset.current.x,
            viewOffset.current.y,
            size.width,
            size.height
          );
          camera.updateProjectionMatrix();
        };
      }, [camera, size]);
    
      useFrame((_, delta) => {
        controls.current?.update(delta);
      });
    
      return (
        <>
          <CameraControls makeDefault ref={controls} />
          <mesh>
            <boxGeometry args={[1, 1, 1]} />
            <meshBasicMaterial color="red" wireframe />
          </mesh>
          <gridHelper args={[50, 50]} position-y={-1} />
        </>
      );
    }
    
    export default function App() {
      return (
        <Canvas
          className="fullscreen"
          camera={{ position: [0, 0, 5], fov: 60, near: 0.01, far: 100 }}
        >
          <OffSet />
        </Canvas>
      );
    }
    

    编辑

    一般来说,这是一个自定义偏移的问题。你可以像原始示例一样setViewOffset“平移”场景。我根据你示例的参数重新创建了原始示例,结果也与原先一样:

    CodePen 上有原文

    import * as THREE from "https://esm.sh/three";
    import CameraControls from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm';
    import { Reflector } from "https://esm.sh/three/addons/objects/Reflector.js"
    
    CameraControls.install( { THREE: THREE } );
    const width = window.innerWidth;
    const height = window.innerHeight;
    const clock = new THREE.Clock();
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera( 60, width / height, 0.01, 100 );
    camera.position.set( 0, 0, 5 );
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize( width, height );
    document.body.appendChild( renderer.domElement );
    
    let offsetUpdated = false;
    const viewOffset = new THREE.Vector2();
    const cameraControls = new CameraControls( camera, renderer.domElement );
    cameraControls._truckInternal = ( deltaX, deltaY ) => {
    
        viewOffset.x += deltaX;
        viewOffset.y += deltaY;
    
        camera.setViewOffset(
            width,
            height,
            viewOffset.x,
            viewOffset.y,
            width,
            height,
        );
        camera.updateProjectionMatrix();
        offsetUpdated = true;
    
    }
    
    const mesh = new THREE.Mesh(
        new THREE.BoxGeometry( 1, 1, 1 ),
        new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: false } )
    );
    mesh.position.y=0.6;
    scene.add( mesh );
    
    const loader = new THREE.TextureLoader();
    const gridEmitTexture = loader.load("https://media.craiyon.com/2023-11-26/2ets6-v1SVGOdKAtPxmlMw.webp");
    
    const reflector = new Reflector(
      new THREE.PlaneGeometry(120, 120),
      {
        clipBias:       0.003,
        textureWidth:   2048,
        textureHeight:  2048,
        color:          0xededed,
      }
    );
    
    reflector.rotation.x = - Math.PI / 2;
    reflector.position.y = 0;
    
    const emissivePlane = new THREE.Mesh(
      new THREE.PlaneGeometry(120, 120),
      new THREE.MeshBasicMaterial({
        map:             gridEmitTexture,
        transparent:     true,
        opacity:         0.8,
        depthWrite:      false
      })
    );
    emissivePlane.rotation.x = - Math.PI / 2;
    emissivePlane.position.y = 0.001;
    
    scene.add(reflector, emissivePlane);
    
    renderer.render( scene, camera );
    
    ( function anim () {
    
        const delta = clock.getDelta();
        const elapsed = clock.getElapsedTime();
        const updated = cameraControls.update( delta );
    
        requestAnimationFrame( anim );
    
        if ( updated || offsetUpdated ) {
    
            renderer.render( scene, camera );
            offsetUpdated = false;
            console.log( 'rendered' );
    
        }
    
    } )();
    
    globalThis.THREE = THREE;
    globalThis.cameraControls = cameraControls;
    
    

    通过反复试验,我找到了一个使用monkey-patching 的解决方案,它可以消除伪影。对反射器进行 monkey-patching,使其自身的虚拟相机在绘制到反射之前始终清除所有视图偏移。

    camera.setViewOffset( fullWidth, fullHeight, offsetX, offsetY, viewWidth, viewHeight );
    camera.updateProjectionMatrix();
    

    setViewOffset改变相机视锥体,告诉 Three.js 只渲染完整视锥体的一部分,同样的方式也会影响使用该相机的所有对象。Reflector 会virtualCamera复制你的相机……然后执行

    virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
    

    复制投影矩阵会包含视图偏移,而视图偏移通常位于镜像视图之外,从而拉伸反射纹理。这会导致上述瑕疵。

    CodePen 上有onBeforeRender

    import * as THREE from "https://esm.sh/three";
    import CameraControls from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm';
    import { Reflector } from "https://esm.sh/three/addons/objects/Reflector.js";
    
    CameraControls.install({ THREE });
    
    const width  = window.innerWidth;
    const height = window.innerHeight;
    
    const scene    = new THREE.Scene();
    const camera   = new THREE.PerspectiveCamera(60, width/height, 0.01, 100);
    camera.position.set(0, 0, 5);
    
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(width, height);
    document.body.appendChild(renderer.domElement);
    
    const clock    = new THREE.Clock();
    const controls = new CameraControls(camera, renderer.domElement);
    
    let viewOffset = new THREE.Vector2();
    controls._truckInternal = (dx, dy) => {
      viewOffset.x += dx;
      viewOffset.y += dy;
      camera.setViewOffset(
        width, height,
        viewOffset.x, viewOffset.y,
        width, height
      );
      camera.updateProjectionMatrix();
    };
    
    const reflector = new Reflector(
      new THREE.PlaneGeometry(120, 120),
      { clipBias: 0.003, textureWidth: 2048, textureHeight: 2048, color: 0xededed }
    );
    reflector.rotation.x = -Math.PI / 2;
    reflector.position.y = 0;
    
    const _orig = reflector.onBeforeRender;
    reflector.onBeforeRender = function(renderer, scene, cam){
      const saved = cam.view ? { ...cam.view } : null;
      cam.clearViewOffset();
      cam.updateProjectionMatrix();
      _orig.call(this, renderer, scene, cam);
      if (saved) {
        cam.setViewOffset(
          saved.fullWidth, saved.fullHeight,
          saved.offsetX,  saved.offsetY,
          saved.width,    saved.height
        );
        cam.updateProjectionMatrix();
      }
    };
    
    scene.add(reflector);
    
    const loader = new THREE.TextureLoader();
    const gridTex = loader.load("https://media.craiyon.com/2023-11-26/2ets6-v1SVGOdKAtPxmlMw.webp");
    
    const emissivePlane = new THREE.Mesh(
      new THREE.PlaneGeometry(120, 120),
      new THREE.MeshBasicMaterial({
        map: gridTex,
        transparent: true,
        opacity: 0.8,
        depthWrite: false
      })
    );
    emissivePlane.rotation.x = -Math.PI/2;
    emissivePlane.position.y = 0.001;
    scene.add(emissivePlane);
    
    const box = new THREE.Mesh(
      new THREE.BoxGeometry(1,1,1),
      new THREE.MeshBasicMaterial({ color: 0xff0000 })
    );
    box.position.y = 0.6;
    scene.add(box);
    
    renderer.render(scene, camera);
    
    function animate() {
      const delta = clock.getDelta();
      controls.update(delta); 
      renderer.render(scene, camera);
      requestAnimationFrame(animate);
    }
    animate();
    

    重写代码 R3F

    顺便说一句,请记住“... R3F 反射器/MeshReflectorMaterial 与三的反射器不同...” - 您可能会很难重新创建代码 Vanilla → R3F 1-1...

    点击此处查看更多

    import React, { useRef, useEffect } from "react";
    import { Canvas, useThree, useFrame, useLoader } from "@react-three/fiber";
    import * as THREE from "three";
    import CameraControls from "camera-controls";
    import { TextureLoader } from "three";
    import { Reflector } from "three/examples/jsm/objects/Reflector.js";
    import "./styles.css";
    
    CameraControls.install({ THREE });
    
    function Offset() {
    const controls = useRef();
    const reflectorRef = useRef();
    const { camera, gl, scene, size } = useThree();
    const clock = useRef(new THREE.Clock());
    const viewOffset = useRef(new THREE.Vector2(0, 0));
    const gridTex = useLoader(
    TextureLoader,
    "https://media.craiyon.com/2023-11-26/2ets6-v1SVGOdKAtPxmlMw.webp"
    );
    
    useEffect(() => {
    controls.current = new CameraControls(camera, gl.domElement);
    
    controls.current._truckInternal = (dx, dy) => {
    viewOffset.current.x += dx;
    viewOffset.current.y += dy;
    camera.setViewOffset(
    size.width,
    size.height,
    viewOffset.current.x,
    viewOffset.current.y,
    size.width,
    size.height
    );
    camera.updateProjectionMatrix();
    };
    
    return () => controls.current?.dispose();
    }, [camera, gl, size]);
    
    useEffect(() => {
    const reflector = new Reflector(new THREE.PlaneGeometry(120, 120), {
    clipBias: 0.003,
    textureWidth: 2048,
    textureHeight: 2048,
    color: 0xededed,
    });
    
    reflector.rotation.x = -Math.PI / 2;
    reflector.position.y = 0;
    
    const orig = reflector.onBeforeRender;
    reflector.onBeforeRender = function (renderer, scene, cam) {
    const saved = cam.view ? { ...cam.view } : null;
    cam.clearViewOffset();
    cam.updateProjectionMatrix();
    orig.call(this, renderer, scene, cam);
    if (saved) {
    cam.setViewOffset(
    saved.fullWidth,
    saved.fullHeight,
    saved.offsetX,
    saved.offsetY,
    saved.width,
    saved.height
    );
    cam.updateProjectionMatrix();
    }
    };
    
    reflectorRef.current = reflector;
    scene.add(reflector);
    
    return () => {
    scene.remove(reflector);
    };
    }, [scene]);
    
    useFrame(() => {
    const delta = clock.current.getDelta();
    controls.current?.update(delta);
    });
    
    return (
    <>
    <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.001, 0]}>
    <planeGeometry args={[120, 120]} />
    <meshBasicMaterial
    map={gridTex}
    transparent
    opacity={0.8}
    depthWrite={false}
    />
    </mesh>
    
    <mesh position={[0, 0.6, 0]}>
    <boxGeometry args={[1, 1, 1]} />
    <meshBasicMaterial color="red" />
    </mesh>
    </>
    );
    }
    
    export default function App() {
    return (
    <Canvas
    camera={{ position: [0, 0, 5], fov: 60, near: 0.01, far: 100 }}
    gl={{ antialias: true }}
    >
    <Offset />
    </Canvas>
    );
    }
    

    CODESANDBOX

    • 1

相关问题

  • 线性深度、透视深度和正交深度之间有什么区别?

  • 是否可以使用 Autodesk APS 创建 3D 建筑配置器?或者 Three.js 更好?

  • 在 Three.js 中旋转 hdr 地图

  • 使用 GLTFLoader 加载的模型未正确渲染

  • 使用 React 三纤维制作顶点上有点的网格

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve