Insert a 3D model at the location where the mouse is clicked using the three.js library

:

I am attempting to incorporate a 3D model into the scene upon mouse click, where the mesh should align with the point clicked by the mouse. This involves utilizing raycasting and projection techniques.

The code for the mouseClick event is as follows:

var Material = new THREE.MeshLambertMaterial({color : 0xfb0000});
Material.side = THREE.DoubleSide;


function mouseClick(event) {
    var mouse3D = new THREE.Vector3(( event.clientX / window.innerWidth ) * 2 - 1,
    -( event.clientY / window.innerHeight ) * 2 + 1,
    0.5);

    var Projector = new THREE.Projector();
    Projector.unprojectVector(mouse3D, Camera);
    mouse3D.sub(Camera.position);
    mouse3D.normalize();

var raycaster = new THREE.Raycaster(Camera.position, mouse3D,0.1,100000);
var intersects;


intersects = raycaster.intersectObjects(Scene.children);
if (intersects.length > 0) {

    var Mesh = new THREE.Mesh(ArrowGeometry, Material);
    Mesh.scale.set(0.05,0.05,0.05);
    Scene.add(Mesh);
    Mesh.name = "arrow";

    if(Scene.getObjectByName("arrow")!= undefined) {
        console.log("added");
    }
  console.log(intersects[0].point);
}

}


document.addEventListener('mousedown', mouseClick, false);

However, when the mesh position is set to 'intersects[0].point', the mesh is not visible. Here is the remaining code:

var Renderer;
var Scene;
var Light1;
var Camera;
var Mesh;
var Width;
var Height;
var Controls ;
var ArrowGeometry;

function initialize()
{
    Width = window.innerWidth;
    Height = window.innerHeight;

    Renderer = new THREE.WebGLRenderer({antialias: true, alpha: true})
    Renderer.setSize(Width, Height);
    document.body.appendChild(Renderer.domElement);
    Renderer.setClearColor(0x000000, 0);

    Scene = new THREE.Scene();

    Camera = new THREE.PerspectiveCamera(45, Width/Height, 0.1, 10000);
    Camera.position.set(3, 12, 13);
    Scene.add(Camera);

    Light1 = new THREE.HemisphereLight(0xffffff, 0x080820, .8);
    Light1.position.y = 100;
    Scene.add(Light1);

    var Geometry = new THREE.PlaneGeometry(20, 20);
    var Material = new THREE.MeshLambertMaterial({color: 0xf6b68a});
    Material.side = THREE.DoubleSide;
    var Mesh = new THREE.Mesh(Geometry, Material);
    Mesh.rotateX(Math.PI/2);
    Mesh.name = "plane";
    Scene.add(Mesh);

    var Loader = new THREE.JSONLoader();
    Loader.load('models/arrow.json',function(geometry){

        ArrowGeometry = geometry;

    });


    Controls = new THREE.OrbitControls(Camera, Renderer.domElement);

    function animate()
    {
        requestAnimationFrame(animate);
        Renderer.render(Scene, Camera);

    }

    window.onload = function()
    {
        initialize();
        animate();
    }
}

Answer №1

Adjusting the mesh position to coordinates x, y, and z based on the intersects array index 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

What is the best way to utilize Gulp and Browserify for my JavaScript application?

Looking to modernize my app with a new build system and I could use some guidance. It seems like I need to shift my approach in a few ways. Here's the current structure of my app: /src /components /Base /App.jsx /Pages.jsx /. ...

Encountering an error stating "ngbCollapse" is not a recognized property of "div" after relocating components to a sub module

Error compiler.js:215 Uncaught Error: Template parse errors: Can't bind to 'ngbCollapse' since it isn't a known property of 'div'. ("][ngbCollapse]="isHidden" In the process of organizing my code, I encountered an issue ...

Do search engines crawl through JavaScript-generated keyword and description meta tags?

My website loads its template via ajax, with the description and keywords meta tags present on the template.html file rather than the current index.html page. Once the template is loaded, it embeds the meta tags into the index.html file. I'm wonderin ...

Is it possible to utilize AngularJS's $q functionality outside of an Angular component?

I am currently working on a browser application, where I have a specific file responsible for creating and initializing an object. This file is written in plain Javascript rather than being part of the Angular ecosystem like the rest of the app, which is b ...

What is the best way to implement dynamic variables in ng-model-options?

I am experiencing an issue with the ng-model-options not updating as expected. For instance, if you input 4:00 pm in both time fields in the snippet below, you'll notice that the UTC output differs - the first is 6 and the second is 8. This behavior i ...

Setting the overlay video to match the input video size in FFMPEG

Currently, I am incorporating FFMPEG wasm into a NextJS project. However, I believe that general FFMPEG solutions will suffice since FFMPEG wasm is capable of interpreting standard FFMPEG commands. My objective is to superimpose an overlay video onto the ...

Activate the drop-down division when the search box is in focus with xoxco technology

Currently, I am incorporating Xoxco's tag input plugin which can be found at the following link: In my customization, I have implemented JQuery's focus() function <input id="tags_1" class="tag-holder" type="text" class="tags" /></p> ...

When using Three.js to load a gltf model and applying a color to it, the model appears normal. However, upon zooming out

Greetings to all, I've encountered an unusual issue while working with a glTF model in three.js. When I zoom into the model, it displays colors as expected. However, when I zoom out, the entire model appears black. Interestingly, setting color directl ...

Using TypeScript with React and Redux to create actions that return promises

Within my React application, I prefer to abstract the Redux implementation from the View logic by encapsulating it in its own package, which I refer to as the SDK package. From this SDK package, I export a set of React Hooks so that any client can easily u ...

Reactjs: Tips for precisely cropping an image to a specific aspect ratio using client-side techniques

Looking to crop an image with a minimalist approach to achieve a specific aspect ratio. For instance, if we have an image sized at 3038 x 2014 px, and desire a 1:2 aspect ratio, we would crop it to 3021 x 2014 px. The crop would be made from the center of ...

React Router Link Component Causing Page Malfunction

Recently, I delved into a personal project where I explored React and various packages. As I encountered an issue with the Link component in React Router, I tried to find solutions online without any luck. Let me clarify that I followed all installation st ...

The value of a string in jQuery turns undefined once it is used as an argument

Hello there, Currently, I am working on a personal project involving NodeJS and Electron. The project is a basic text editor as of now. However, I am facing an issue when attempting to pass the value of a text-area to a function before saving it to a file ...

What is the best way to create a dynamic text area that changes based on a dropdown selection?

I'm trying to create a feature on my form where selecting a retailer from a dropdown menu automatically generates a corresponding link next to the textbox. For example, if someone picks Best Buy, I want a link to bestbuy.com to show up immediately wit ...

Using the mt-downloader module in a Node application is a straightforward process

Hey there, I'm looking to incorporate the Multi downloader module into my project. I've checked out the GitHub link, but unfortunately, there are no examples provided on how to actually use this module. I came across this example and tried implem ...

The error message "TypeError: undefined in JavaScript Vue's V-for loop

I created a function that generates an array of objects in this format: getMonthDaysGrid() { const totalLastMonthDays = this.getFirstDayOfMonth().dayNumber; const totalDays = this.month.numberOfDays + totalLastMonthDays; const monthList = Array ...

Inquiring about how to make the pieces move on the checker boards I created

I'm having trouble getting my SVG pieces to move on the checkerboard. Can someone please help me figure out how to make them move, even if it's not a valid move? I just want to see them in motion! The important thing is that the pieces stay withi ...

Executing a function in Node-Express with a database connection at the beginning of the application

I am relatively new to Node.js and currently working on a Node.js - Express solution as a back-end for an AngularJS web application. My goal is to send an email when the MSSQL database query returns specific information. I have successfully implemented thi ...

Is it possible to pass parameters in the .env file in Node.js?

I am storing my file users.env inside routes/querys/users.env module.exports = { GET_USERS: "SELECT * FROM users", CREATE_USER: "INSERT INTO users ("id", "first_name", "last_name", "active") VALUES (NULL, '%PARAM1%', '%PARAM2%', & ...

I'm having trouble with my next.js code that is supposed to handle dynamic content and routing

Currently, I am following a YouTube tutorial to learn next.js and have encountered an issue right at the beginning. I am attempting to develop dynamic content and routing for my website using the code snippet below, but I am facing an error: import Link fr ...

Attempting to configure a webhook eventsub through the Twitch API by utilizing ngrok as the intermediary

After triggering a test event using the Twitch CLI, an error response was received indicating: Post "https://1562-5-182-32-19.ngrok.io/api/twitch/eventsub/": context deadline exceeded (Client.Timeout exceeded while awaiting headers). The notification even ...