Retrieve an object in Three.js using the objloader and its name

I've been struggling for weeks to manipulate OBJLOADED objects in a three.js scene using keyboard buttons. My goal is to translate and rotate the objects based on key inputs, such as pressing 'A' to translate objA along the X-axis and 'B' to translate objB.

function addObject(model) {
   var mtlLoader = new THREE.MTLLoader();
   var objLoader = new THREE.OBJLoader();

   mtlLoader.load(model+'.mtl', function (materials) {
    materials.preload();       
    objLoader.setMaterials(materials);

    objLoader.load(model+'.obj', function (object) {        
        object.name =model;
        scene.add(object);        
        // I'm struggling with returning an object here
    });
});
}   

var obj1 = scene.getObjectByName('objA');

if(obj1.name=='objA'){
    alert('Yes');
}

I can't seem to get this code to work as intended. Any suggestions or solutions would be greatly appreciated!

Answer №1

To implement object interaction in your scene, you can create a map to store the objects you wish to work with.

var interactableObjects = {};

function addObjectToScene(model) {
   var mtlLoader = new THREE.MTLLoader();
   var objLoader = new THREE.OBJLoader();

   mtlLoader.load(model+'.mtl', function (materials) {
    materials.preload();       
    objLoader.setMaterials(materials);

    objLoader.load(model+'.obj', function (object) {        
        object.name = model;
        scene.add(object);        

        interactableObjects[model] = object;
    });
  });
}

addObjectToScene('modelA');
addObjectToScene('modelB');

function handleKeyPress(event) {
    switch(event.keyCode) {
        case 65:
            interactableObjects['modelA'].translateX(1);
            break;
        case 66:
            interactableObjects['modelB'].translateX(1);
            break;
    }
}

window.addEventListener('keypress', handleKeyPress);

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

Discovering the method to extract a Specific Form Field value with JQuery

Recently, I encountered a form that looked like this: <form id="post_comment" action="cmt.php" method="post"> <input type="hidden" name="type" value="sub" /> <textarea id="body"></textarea> </form> To interact with the ...

Tips for making a bookmark for your iframe content

Within this HTML code, there is a list element with the ID "about_ma" and an iframe named "page" that is initially hidden. <div id="navigation"> <ul id="nav"> <li id="about_ma"><a href="index1.php?name=about.php">Ab ...

The React Component is not displaying any content on the webpage

I developed a Reactjs application using the create-react-app. However, I am facing an issue where the components are not displaying on the page. I suspect that App.js is failing to render the components properly. Take a look at my code: App.js import R ...

What measures does Redux take to ensure race conditions do not occur?

Recently, I delved into Redux and grasped the concept very well. However, there is one particular line in the official documentation that puzzled me: Because all changes are centralized and happen one by one in a strict order, there are no subtle race ...

Swap information in one array with information from a different array

I am working with two arrays: const data = [ { id: 0, identifier: 'free-2020', name: '<I18nText id="pricing.plans.name.free" />', planTitle: 'free', price: '00', ...

Encountering issues with installing @vue/cli on Linux Ubuntu

Currently facing an issue while attempting to install the Vue CLI on Ubuntu (WSL). After running both yarn add global @vue/cli and npm install @vue/cli --global, it seems like the commands were successful. However, upon checking the version using vue --v ...

A method to transfer a floating point number from Python to JavaScript without using cgi

Running an Apache server from a Raspberry Pi, I have a Python script that prints sensor input to the console. A PHP script then processes this output and controls a light based on the sensor reading before printing it again. Everything works fine when exec ...

Text generated dynamically for buttons

I need help with updating the text on dynamically generated buttons. I tried a method below, but it's not working. $(document).on('click', '.class', function(e){ var thisbut = this.id; $.post('my.php',{ val: val1 ...

Module not discovered by nodeJS within the current directory

In my node application, I am trying to incorporate a module called dishRouter. The file structure looks like this :- Structure The dishRouter is exported from Dishes/index.js and imported into my app.js using the following code: var dishRouter = re ...

Tips on changing a div HTML tag through a button's onclick event with javascript

<nav class="navbar navbar-default" style="..."> <div class="container" id="main_container" style="margin-top: -80px"> <div> <div class="row"> <div class="col-xs-0 col-md-2" style="backgroun ...

Unexpected outcome observed with straightforward MongoDB MapReduce task

For the past few hours, I've been struggling with a seemingly simple issue. I have a collection of documents that all have the same structure: { "_id": "736722976", "value": { "tag_cloud": { "0": { "0": "FIFA World Cup 2014 ...

What is the best practice for naming variables in JavaScript?

Currently, my API is built using PHP Laravel and MySQL, which uses snake_case for field names. I am considering using the same naming convention in client-side JavaScript to make it easier to transfer field names from PHP code to JavaScript code and when m ...

I'm looking to incorporate a module from another component (Next.js, React.js) into my project

I need to implement the "StyledSwiperPagination(swiper-pagination-bullet) at SwiperImages.tsx" in "index.tsx". The problem is that when I added <StyledSwiperPagination /> in index.tsx, nothing appeared on the screen. Lorem ipsum dolor sit amet, co ...

Transforming the JSON data into a text format

I have a JSON object structured like this: { "name": "ok", "country": "US", "phone": "900", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f70745f727e767331707c">[email protected]</a>", ...

React-router is failing to redirect properly within a specific component

I have configured react router to redirect from the "/" route to a custom route "/:city/posts", but the redirect is not working as expected. When the button is clicked, the page refreshes. This setup is working fine in other components, so I'm not sur ...

What is the best way to create messages that can function seamlessly in both Java and JavaScript environments?

Utilizing a file named messages.properties with JSTL format messaging has been effective for server-side Java and JSP applications. However, when it comes to incorporating JavaScript, the need arises for the same messages in a format that is compatible w ...

Design an HTML form that includes checkboxes for selecting multiple values

I am encountering an issue with a Checkbox field in an HTML input form. The values for the checkboxes are being fetched from another table and I am trying to select multiple users using these checkboxes. However, it seems like my code is not working as int ...

employing the 'appendTo()' function within a child div nested inside a parent div

After hours of searching, I still haven't found a solution to my specific problem: This is the HTML code I have: <div id="list" style="display:none;"> <div id="insideList"> <!-- Some picture will go here --> </di ...

Guide to setting up Gatsby CLI and Gatsby version 2

Currently, I am working on a project that utilizes Gatsby v2 in its package.json file. However, to run the project, I need to globally install Gatsby-cli as per the documentation. Strangely, the global installation of Gatsby-cli also installs Gatsby v4, ca ...

Ways to show confirmation when the user presses the back browser button?

Similar Question: How can I capture the browser's back button event using JavaScript? In my application, I am looking to implement a feature where only certain scripts (Text1.php, Text2.php, and Text3.php) will trigger a confirmation box when the ...