Within my Vue component, I have integrated a threejs scene and I am facing an issue with selecting objects using the mouse. I am currently using the OnPointerDown event and raycaster to locate objects under the mouse pointer. However, it seems like the raycasting code is positioning each object slightly off from its actual location, possibly due to the camera's width and height settings. I am working on a 2D scene using an OrthographicCamera with no rotation.
The structure of my app is as follows:
<template style="height:100vh">
<v-container fluid style="height: 100vh;" >
<v-layout fill-height>
<ViewPort />
</v-layout>
</v-container>
</template>
ViewPort
is a component that I will summarize briefly here:
<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();
}
})
Initialization:
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);
}
Handling object selection on pointer down:
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
}
}
I am unsure about the correct way to define the size of the threejs camera within the component. Currently, when an object is selected, its color changes. How should I accurately set the camera size? I aim for this component to be versatile and adaptable to any usage scenario. What am I overlooking or doing incorrectly?