Threejs射线投射器击中物体时稍微在物体的外面



我在一个value组件中有一个三个ejs场景。我需要能够使用鼠标选择对象,并使用OnPointerDown事件和光线投射器来查找鼠标指针下的对象。这几乎可以工作,但似乎光线投射的代码是将每个对象定位在它真正所在的位置的左边和上面。我认为这可能与相机的宽度和高度等有关,但我不知道是什么。我实际上是通过使用没有旋转的OrthographicCamera创建一个2D场景

我的应用程序是这样的:

<template style="height:100vh">
<v-container fluid style="height: 100vh;" >
<v-layout fill-height>
<ViewPort />
</v-layout>
</v-container>
</template>

ViewPort是我的组件,它太大了,不能在这里发布,所以我只发布关键部分:

<script lang="ts">
import * as THREE from "three";
import { Component, Vue } from "vue-property-decorator";
@Component<ViewPort>({
components: {},
mounted() {
this.init();
const container = document.getElementById('container');
if (container) container.appendChild(this.renderer.domElement);
this.animate();
}
})

初始化

private init() {
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0xf0f0f0);
const container = document.getElementById('container');
if (!container) return;
const width = container.clientWidth;
const height = container.clientHeight;
this.camera = new THREE.OrthographicCamera(
-width / 2,
width / 2,
100,
-height + 100
);
this.camera.position.set(0, 0, 1000);
this.scene.add(this.camera);
this.renderer.setSize(width, height);
this.renderer.shadowMap.enabled = false;
document.addEventListener("pointerdown", this.onPointerDown, false);
window.addEventListener("resize", this.onWindowResize, false);
}

获取指针向下的相交对象:

private onPointerDown(event: any) {
this.node = undefined;
this.onDownPosition.x = event.clientX;
this.onDownPosition.y = event.clientY;
const container = document.getElementById('container');
if (container){
this.pointer.x = (event.clientX / container.clientWidth) * 2 - 1;
this.pointer.y = -(event.clientY / container.clientHeight) * 2 + 1;
}
this.raycaster.setFromCamera(this.pointer, this.camera);
const intersects = this.raycaster.intersectObjects(
this.scene.children,
true
);
if (intersects.length > 0) {
//do stuff
}
}

我不知道我应该做些什么来设置三个镜头的大小等等。这里写着"做某事"我改变物体的颜色来选择它。我应该如何设置相机的尺寸?我希望上面的组件可以在任何地方使用,因此场景可以适当地设置其大小等。我做错了什么?

我来回答我自己的问题:

if (container){
this.pointer.x = (event.clientX / container.clientWidth) * 2 - 1;
this.pointer.y = -(event.clientY / container.clientHeight) * 2 + 1;
}

应:

if (container){
this.pointer.x = (event.offsetX/ container.clientWidth) * 2 - 1;
this.pointer.y = -(event.offsetY/ container.clientHeight) * 2 + 1;
}

最新更新