【发布时间】:2021-04-30 08:32:29
【问题描述】:
我在一个 vue 组件中有一个 threejs 场景。我需要能够使用鼠标选择对象,并使用 OnPointerDown 事件和 raycaster 来查找鼠标指针下的对象。这几乎可以工作,但似乎光线投射的代码将每个对象稍微定位在其实际位置的左侧和上方。我认为这可能与相机的宽度和高度等有关,但我不知道是什么。我实际上是通过使用没有旋转的 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
}
}
我不知道我应该做什么来设置threejs相机的大小等。所以在它说“做东西”的地方我改变了对象的颜色来选择它。我应该如何设置相机尺寸?我希望上述组件可以在任何地方使用,因此场景可以适当地设置其大小等。我做错了什么?
【问题讨论】:
标签: typescript vue.js three.js