Converting Mesh to Object3D: A step-by-step guide

Currently utilizing Typescript alongside Webpack. To create a 3D floor using three.js, I have integrated multiple plane objects (100 in total) with a seamless image serving as their background:

import {
    Scene,
    PerspectiveCamera,
    WebGLRenderer,
    TextureLoader,
    PlaneGeometry,
    MeshBasicMaterial,
    Mesh,
} from 'three'
import ground from './ground.jpg'


class Game {
    private readonly scene: Scene = new Scene()
    private readonly camera: PerspectiveCamera = new PerspectiveCamera()
    private readonly renderer: WebGLRenderer = new WebGLRenderer()

    constructor() {
        document.body.style.margin = "0"
        document.body.style.overflow = "hidden"
        document.body.appendChild(this.renderer.domElement)
        this.resizeCanvas()
        window.addEventListener("resize", this.resizeCanvas.bind(this))
        this.setupCamera()
        this.initiateGround()
        this.render()
    }

    private initiateGround() {
        const texture = new TextureLoader().load(ground);
        const geometry = new PlaneGeometry(1, 1);
        const material = new MeshBasicMaterial({map: texture});


        for (let i = 0; i < 100; i++) {
            for (let j = 0; j < 100; j++) {
                const plane = new Mesh(geometry, material);
                this.scene.add(plane);
                plane.position.set(i - 50, j - 50, 1);
            }
        }

        this.camera.position.z = 5;
        this.camera.rotation.x = .6;
    }


    private resizeCanvas(): void {
        this.renderer.setSize(window.innerWidth, window.innerHeight)
        this.camera.aspect = window.innerWidth / window.innerHeight
        this.camera.updateProjectionMatrix()
    }


    private setupCamera() {
        this.camera.fov = 75
        this.camera.near = .001
        this.camera.far = 100
        this.camera.updateProjectionMatrix()
    }


    private render() {
        requestAnimationFrame(this.render.bind(this))
        this.renderer.render(this.scene, this.camera)
    }
}

new Game()

To optimize performance, my aim was to only display the planes visible to users. Upon researching, I came across this solution:

const intersects = new Raycaster().intersectObjects(theObject);
if ( intersects.length > 0 ) {
     // Hide if index > 0
}

However, when attempting to determine if the plane is within view of the user's camera, I encountered this error:

Argument of type 'Mesh<PlaneGeometry, MeshBasicMaterial>' is not assignable to parameter of type 'Object3D<Event>[]'.

This indicates the need to convert the mesh to Object3D. Despite searching online, I couldn't find a suitable solution. Hence, I am reaching out to ask this question.

I welcome any feedback on other sections of my code, as it may not be flawless.

Answer №1

I realized all I had to do was include []:

const hits = new Raycaster().findIntersectingObjects([targetObject]);
if ( hits.length > 0 ) {
     // Concealed when the index is greater than 0
}

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

Example using three.js showing issues with external resources failing to load on jsfiddle.net

Currently, I am endeavoring to make progress with this sample project: github.com/josdirksen/learning-threejs/blob/master/chapter-09/07-first-person-camera.html I have made attempts at replicating the code on my personal pages.github.io account and also m ...

Powering up your React components with MDX, Storybook, and Typescript!

Currently, I am attempting to incorporate MDX markup into the creation of live documentation for my storybook. However, upon running the storybook, an error is occurring: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: C ...

Tips for maintaining an open ng-multiselect-dropdown at all times

https://www.npmjs.com/package/ng-multiselect-dropdown I have integrated the ng multiselect dropdown in my Angular project and I am facing an issue where I want to keep it always open. I attempted using the defaultOpen option but it closes automatically. ...

Why is it that in reactive forms of Angular, the parameter being passed in formControlName is passed as a string?

I am currently working on a reactive form in Angular. In order to synchronize the FormControl object from the TypeScript file with the form control in the HTML file, you need to utilize the formControlName directive. This is accomplished as shown below: f ...

A Guide to Handling Errors while Converting a Map to a Promise in Typescript

I am attempting to capture errors if any of the asynchronous code within my map function fails. It seems to enter the error block but does not log anything, as the error variable remains null. Is there an alternative method for handling errors within map ...

Managing dynamic text within a label using Playwright

In my Playwright Typescript test, I have the following code snippet: await page.goto('https://demoqa.com/'); await page.getByLabel('Optionen verwalten', { exact: true }).click(); await page.locator('label').filter({ hasText: & ...

Encountered Error: Rendered an excessive number of hooks beyond the previous render in the framework of Typescript and

I am currently working on integrating Typescript and Context API in an application. Specifically, I am focusing on setting up the Context API for handling login functionality. However, I encountered the following error message: Error: Rendered more hooks ...

Webpack 4 combines the power of Vue with the versatility of Typescript classes and JavaScript code simultaneously

Currently, I am in the process of migrating JS files to Typescript with the objective of being able to utilize both JS and Typescript classes within Vue. While I understand that I can convert Vue scripts into Typescript, I prefer not to do so at this momen ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions: The denominator remains constant The numerator must be unique and fall within the range of 1 to three times the denominator The fraction should not be reducible (e.g., 2/6 ...

The "if(x in obj)" statement in Typescript does not properly narrow down my custom Record

I am struggling with a code snippet where I am trying to check if a string exists in my custom record using the if(x in obj) guard statement, but it seems to not be working as expected. Below is the sample code snippet that is throwing an error: type Ans ...

Changing the format of a numerical value to include commas for every 1000 increment

I'm trying to find a way to format numbers in a specific manner, such as changing 1234567 into 1,234,567. However, I've run into some issues when attempting to use the currency pipe of TypeScript. It adds USD or $ in front of the number, which i ...

Trouble with maps not showing up and the console isn't showing any errors when using @react-google-m

Currently, I am facing an issue while trying to integrate Google Maps by following a blog post that provides instructions on next13 TypeScript. Despite reaching the point where the maps should be displayed, nothing appears on the screen. Surprisingly, ther ...

Ways to resolve the issue of the 'setConfirmDelete' property not being found on type 'JSX.IntrinsicElements' in React.js

index.tsx const setConfirmDelete = (state, close) => { return ( <Modal show={state} onHide={close}> <Modal.Header> <Modal.Title>Title</Modal.Title> </Modal.Header> <Modal.Body> 'T ...

Tips for preventing Angular from requiring an additional tag for a child component

Consider a scenario where I have a parent and child component in Angular 12. Their templates are structured as follows: Parent: <h1>This is the parent component</h1> <div class="container"> <div class="row"> ...

What Google Domain Verification APIs are needed for verifying domains in Pub/Sub?

I've written this code that utilizes a Domain token to verify a domain with Google using the Site Verification API: const auth = await this.gcp.getApplicationCredential(accountId, projectId,[ 'https://www.googleapis.com/auth/siteverification ...

How can I populate dropdown options from an API in a react JS project using typescript and react saga?

Check out my page, where I am trying to fetch brand options from an API. Below is the saga I have implemented: Action.tsx export const getBrandsForDropdown = (request: IPagination) => { return { type: actions, payload: request ...

Error: Failed to execute close function in inappbrowser for Ionic application

Working on integrating the "in-app-browser" plugin with my Ionic project. Check out the code snippet below: const browser = this.iab.create(mylink, '_blank'); browser.on('loadstop').subscribe( data => { if ...

Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter. I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by ...

Troubleshooting connectivity problems: SocketIO integration with microservices on a Kubernetes platform

I have organized my system using microservices architecture, with separate services for client interactions, orders, payments, and more. Each of these services runs on its own express server. Now, I am looking to integrate real-time feedback functionality ...