The Threejs Raycaster detects collisions with objects even when the ray is just grazing the surface

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?

Answer №1

Here's a solution to the problem:

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

Update it to:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The function this.saveAlpha is not recognized in the current context at eval

This code features a start button, stop button, and a timer. The goal is to retrieve information from the phone using events like DeviceOrientationEvent, which includes properties such as absolute, alpha, beta, and gamma (referenced in this link: here). I& ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

Is there a way to retrieve prName and prQty from the double array?

Is there a way to extract the values of prName and prQty from the 2D array? html <h1 v-for="item2 in productListAlaCarte" :key="item2"> <td>{{item2.prName}} {{item2.prQty}}</td> ...

Using Vue.js to invoke an external JavaScript function for search functionality

In my vue.js application, I have a list of users with backend pagination. Now I want to implement a search functionality. I attempted to call the method like this: watch: { search: function() { Crud.methods.getItems(); } }, Howe ...

Is it possible to selectively mock certain components of an external module using jest?

I am totally new to using Jest, especially in regards to unit tests, and I am struggling to write a test for a specific scenario. I know that you can mock an external module like this.. jest.mock('@organisation/library', () => ({ Database: j ...

Using V-model with Vue3 Web Components

I am trying to develop a web component using Vue3 to handle inputs and forms. However, I am encountering issues with two-way data binding. I have included the web component in my HTML page. <vue-input-text id="sample_input" name="sample_i ...

Encountering an error when initializing a form array with an existing array of multiple objects in Angular 13: "Control not found with

Hey there, I'm brand new to Angular and I'm trying to set up a form array with an existing array that contains multiple objects. However, I keep encountering the following error: Cannot find control with path: 'variable-> 0 -> id&apo ...

Retrieve [0, 0, 5] instead of UUIDs when making an Axios GET request in a Laravel and Vue JS application

Yesterday, I encountered a seemingly simple problem which turned out to be more complex than I initially thought. Despite my efforts to search for similar questions on Google, I couldn't find any solutions. If there are any related questions that have ...

Use vue.js to add a block of content after every sixth iteration in a loop

Currently, I have a list of offer cards rendering through a loop. I am adding a row div every 3rd column (bootstrap) element. Now, I need to also add another column element (banner block) for every 6th element in order to achieve a layout like the one show ...

Arrange the items that are missing from Array B to be located at the bottom of Array A, organized in a file tree structure

I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure arr ...

Spartacus storefront is having trouble locating the .d.ts file when using Angular/webpack

Seeking help from the SAP Spartacus team. Encountering errors while developing a Spartacus component, specifically with certain Spartacus .d.ts definition files that cannot be resolved. The issue is reproducible in this Github repository/branch: This pr ...

Angular 4 file upload verification: Ensuring safe and secure uploads

Is there a recommended method to validate the file type when uploading a file in an Angular 4 form? Are there any simple ways to accomplish this task? ...

When utilizing a generic type with a class, type T fails to meet the specified constraint

export type ExtractType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>> = { [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: K }>['type']] } export class CommandLineParse ...

Guide on importing images from directories in Vue

As I delve into learning vue.js, a particular issue has surfaced. I am in the process of creating an SFC and encountering difficulties with loading images from the 'src / assets / logo.png' folder. Below is the code snippet: <template> & ...

Issues with include and exclude directives in tsconfig.json are causing problems

I am currently working on a web project that involves organizing folders. Within my project structure, I have subfolders like the following: src/app/shared/models src/app/shared/services src/app/shared/types Each of these subfolders contains additional ...

The Material Table in Angular is having issues with sorting functionality

I tried implementing the basic example from the angular material website, which displays a table with accurate data but the sorting functionality is not working as expected. For reference, you can view the StackBlitz demo here: https://stackblitz.com/edit ...

Ensuring the accurate usage of key-value pairs in a returned object through type-checking

After generating a type definition for possible response bodies, I am looking to create a function that returns objects shaped as { code, body }, which are validated against the typing provided. My current solution looks like this: type Codes<Bodies> ...

Accessing the value of a FormControl in HTML代码

Modifying the value of a form select element programmatically presents an issue. Even after changing the value in the form, the paragraph element "p" remains hidden. However, if you manually adjust the form's value, the visibility of the "p" element ...

Steps for combining a sequence of subsequent subscriptions in RxJS

In my approach, I followed the code below. this.service1.info .subscribe(a => this.service2.getDetails(a.id) .subscribe(b => { this.doStuff(b); }) ); Lately, it has come to my attention that we will be adding more steps that gradu ...

Typescript best practice: limiting global variables per file

I found it very useful in jslint to require declaring all used globals at the beginning of a file using the following syntax: /*global console, document */ Is there a similar feature available in Typescript? I managed to disable the implicit availabilit ...