Development of multiple interactive 3D models for the website

I have created a stunning 3D model of a city featuring 4 unique buildings, and now I want to take it to the next level by making them interactive. My vision is for users to hover over a building and see text appear on top of it, with the option to click and open a modal window for more information. As a beginner in studying Three.js, I would love some advice on how best to achieve this. Should I add each building individually to make them clickable? And is it even possible to create such an interactive experience with 3D objects?

I have come across information about using Raycaster for similar purposes, but I am struggling to grasp how I can implement this into my project.

Answer №1

To start, initialize a Raycaster:

const raycaster = new THREE.Raycaster()

Next, include this within your rendering function (the looped one):

raycaster.setFromCamera(mouse, camera)

If you're unfamiliar, camera represents your camera and mouse should resemble something like this:

const mouse = new THREE.Vector2()

window.addEventListener('mousemove', (event) => {
    mouse.x = event.clientX / sizes.width * 2 - 1
    mouse.y = - (event.clientY / sizes.height) * 2 + 1
})

For those who may not know; a Raycaster casts a ray and is utilized when determining intersecting objects. This allows for the implementation of desired mouse events on objects/meshes/geometries.

Don't overlook adding this line of code as well:

let currentIntersect = null

Subsequently, incorporate this into your rendering function (the looped one):

const modelsToTest = [model1, model2, model3, model4]
const intersects = raycaster.intersectObjects(modelsToTest)

if(intersects.length){
    if(currentIntersect === null){
        //perform actions
        console.log('mouse enter event occurred!')
    }
    currentIntersect = intersects[0]
}
else{
    if(currentIntersect){
        //perform actions
        console.log('mouse leave event occurred!')
    }
    currentIntersect = null
}

Congratulations, you've now simulated the mouseenter and mouseleave events!

The next goal is to implement the click event. This can be easily achieved by inserting this code snippet somewhere in your script:

window.addEventListener('click', () => {
    if(currentIntersect){
        switch(currentIntersect.object)
        {
            case model1:
                // execute actions for model 1 click!
                break

            case model2:
                // execute actions for model 2 click!
                break

            case model3:
                // execute actions for model 3 click!
                break

            case model4:
                // execute actions for model 4 click!
                break
        }
    }
})

Trust this information proves beneficial!

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

Exploring the nuances between Ruby on Rails and the responses from json and JavaScript ajax

I am interested in learning the most effective method for handling an ajax request. Would it be better to send json data and parse it on the client side (for instance using pure), or should I generate javascript at the server side and send back the respo ...

Error: HTML code being displayed instead of form value in Ajax request output

For the past couple of days, I've been struggling with an Ajax issue that I just can't seem to figure out. Despite looking for a solution online, nothing seems to work. Below is the code snippet that's causing me trouble: <!DOCTYPE html& ...

Utilizing jQuery UI Slider for Calculating Percentage

I recently worked on an example where I incorporated 5 sliders, which you can see here: Example: http://jsfiddle.net/redsunsoft/caPAb/2/ My Example: http://jsfiddle.net/9azJG/ var sliders = $("#sliders .slider"); var availableTotal = 100; ...

Complete and submit both forms during a single event

Essentially, I have an event called onclick that takes form data and stores it in a variable. When another function is executed by the user, I want to send that variable through ajax within the function. This is the onclick event (first form): $('#n ...

Tips for accessing and modifying local JSON data in a Chrome Extension

I am working on an extension and need to access and modify a local JSON file within the extension's directory. How can I accomplish this task? ...

JavaScript code to render a string variable passed by the PostController file within the Sails framework

How can I properly display a string variable in the postview.ejs file sent by the PostController.js in Sails? The variable being used is called 'val' [ ejs html javascript Sails express node.js ] PostController.js module.exports = { post : f ...

How to access a particular tab in Bootstrap 5 using an external link

Is there a way to direct users to a specific tab upon clicking a link on another page? Check out the example below: <div class="products-btn"> <a href="products.html#pills-profile">view all</a> </div> On Pro ...

Maximize the sum of diverse numbers effectively

I have an array that contains objects structured like this: [ { "id": 91, "factor": 2, "title": "Test Product", "price": 50, "interval": 1, "setup": 0, "optional": false }, { "id": 92, "factor": 1, "title": "A ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

Having issues with Angular http.post not sending data when using subscribe

I'm currently facing an issue with sending data to my API using post.subscribe. Despite the fact that no errors are being thrown, the data is not being sent successfully. It's important to note that the API itself is functioning perfectly. Belo ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

How can I ensure the header and footer of a Modal stay in place while still allowing the content within the Modal to scroll?

Recently, I have been experimenting with the Modal component and have noticed that when there is long content in the Modal window, the entire modal body begins to scroll. Is there a way to make only the content scroll while keeping the header and footer ...

Using the Facebook marketing API requires a valid Instagram account ID to be provided as a parameter

I've been exploring the capabilities of the Facebook Marketing API once again. After successfully creating Facebook ads using my Node.js app, I now have my sights set on Instagram. My current call to create an AdCreative looks like this: fb.api(&ap ...

Substitute for SendKeys() in Angular JS web pages using Selenium

Currently, I am utilizing selenium automation to streamline the processes of a third-party website. To input data into form fields, I have been employing the SendKeys() method. While this method is functional, it's time-consuming as there are numerous ...

Using JavaScript to store CSS style properties in an array

In the midst of building a React-datagrid project, I am streamlining CSS properties for an array. However, there seems to be redundant CSS properties that I would like to consolidate into an array format. let _columns = []; let commonStyle = {"width":"20 ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

Urgent dependency alert: calling for a necessity (sequelize) in next.js is a vital element

I'm encountering a challenge with integrating sequelize into my Next.js 13 project to connect my API routes with the database. I keep receiving errors that say "Critical dependency: the request of a dependency is an expression." import * as pg from &a ...

Received the error 'Headers cannot be set after they have been sent to the client' upon the second request

I created a web server that acts as a client-side application using socket.io-client and express. This setup is necessary for another project I am working on. The web server emits the posted string and responds by sending the served string when it receive ...

Why is it that comparing the childNodes of two identical nodes results in false, while comparing their innerHTML yields true?

Currently, I am in the process of developing a simple function in Node.js that compares two DOMs. My goal is to not only identify any differences between them but also pinpoint the exact variance. Interestingly, upon reconstructing identical DOMs using jsd ...

Vue.js will trigger the updated() method only when a particular array undergoes changes

Working on a chat feature and looking for a way to automatically scroll to the end of the conversation when new messages are added. The current solution involving the updated() function works well, but there's a complication with a vue-timepicker com ...