【问题标题】:Clickable element with ThreeJS PerspectiveCamera带有 ThreeJS PerspectiveCamera 的可点击元素
【发布时间】:2021-02-26 14:41:59
【问题描述】:

我用 PerspectiveCamera 创建了一张全景图像,一切顺利。我还设法添加了控件。 现在我想在场景中放置一个可点击元素(链接/按钮/其他),但我不知道如何添加和定位可点击元素……每一个提示/建议都非常感谢!到目前为止,这是我的代码:

function init() {

    const container = document.getElementById( 'three-image' );

    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1100 );

    scene = new THREE.Scene();

    const geometry = new THREE.SphereGeometry( 500, 60, 40 );
    // invert the geometry on the x-axis so that all of the faces point inward
    geometry.scale( - 1, 1, 1 );

    //let imageLocation = <?php echo $block->getPanoramaImages();?>;
    let imageLocation = '/three/luifel.jpg';
    //alert(imageLocation)

    const texture = new THREE.TextureLoader().load(imageLocation);
    const material = new THREE.MeshBasicMaterial( { map: texture } );

    const mesh = new THREE.Mesh( geometry, material );

    scene.add( mesh );

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    container.style.touchAction = 'none';
    container.addEventListener( 'pointerdown', onPointerDown );

    document.addEventListener( 'wheel', onDocumentMouseWheel );

    window.addEventListener( 'resize', onWindowResize );

}

【问题讨论】:

  • 我认为您正在寻找 Raycaster。 Here it is in the docs,您也可以看到它in action in the exaples。该示例激活了“mousemove”上的每个方块,因此您可以添加具有相同逻辑的“click”事件侦听器。

标签: three.js


【解决方案1】:

如果您希望将 html 元素附加到 3d 元素,您可以将 3d 位置投影到 2d 并使用它。

var vector = new THREE.Vector3(100,0,0); // some point
vector.project(camera);


var widthHalf =  window.innerWidth / 2;
var heightHalf = window.innerHeight / 2;

vector.x = vector.x * widthHalf + widthHalf;
vector.y = -(vector.y * heightHalf) + heightHalf;
vector.z = 0;

如果要附加到对象,请使用对象在世界空间中的位置:

vector.setFromMatrixPosition(obj.matrixWorld);
vector.project(camera);

...等

编辑: 我在这里创建了一个示例: https://codepen.io/flatworldstudio/pen/LYbgvgY

【讨论】:

  • 嗨 flatworldstudio,问题是我希望将 html 元素添加到 3d 元素(在我的例子中是透视相机)。我明白你的意思,但是 var vector = new THREE.Vector3(100,0,0); 的 html(对象)在哪里?假设我有一个
    并想将它添加到场景中......我该如何添加它? (对不起,我是初学者...... :))
猜你喜欢
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-29
相关资源
最近更新 更多