The issue I am encountering is that the keyboard controls in JavaScript are not causing the

One of the key elements in my code revolves around JavaScript functionality. I have implemented a feature where objects can be moved by pressing keys such as "down" or "right". However, there seems to be an issue where an object loaded from a .json file is moving correctly, but another object from a .obj file is not responding to the movement commands. Is there a way to troubleshoot and resolve this issue?

This is the snippet of the code in question:

<script>
var container, scene, camera, renderer, controls, stats;
var keyboard = new THREEx.KeyboardState();
var keyboard = new KeyboardState();
var galva;

// Function for initializing the scene
function init() 
{
    // Creating a sphere object
    var spgeometry = new THREE.SphereGeometry( 30, 32, 32 );
    var spmaterial = new THREE.MeshBasicMaterial( {color: 0x00000} );
    galva = new THREE.Mesh( spgeometry, spmaterial );
    galva.position.set(125, 150, 90);
    scene.add( galva );

    // Loading object from a JSON file
    var jsonLoader = new THREE.JSONLoader();
    jsonLoader.load( "models/android.js", addModelToScene );

    // Loading object from a OBJ file
    var loader = new THREE.OBJLoader();
    loader.load("models/teaport.obj", function ( object ) {

        var material = new THREE.MeshLambertMaterial();

        object.traverse( function ( child ) {
            if ( child instanceof THREE.Mesh ) {
                child.material = material;
            }
        } );

        object.scale.set(50,50,50);
        scene.add( object );

    });
}

// Function for adding model to the scene
function addModelToScene( geometry, materials ) 
{
    var material = new THREE.MeshLambertMaterial( materials );
    c = new THREE.Mesh( geometry, material );
    c.scale.set(50,50,50);

    scene.add( c );
}

// Function for updating the scene
function update()
{
    keyboard.update();

    if ( keyboard.down("left") ){ 
        galva.translateX( -50 );
    }

    if ( keyboard.down("right") ){ 
        c.translateX( 50 );
        galva.translateX( 50 );
        object.translateX( 50 );
    }

    controls.update();
    stats.update();
}

Answer №1

To simplify the troubleshooting process, consider sharing a jsfiddle or similar platform with your code. It seems like there may be an issue with variable shadowing and the "object" being undefined. You can try implementing the following change:

var loader = new THREE.OBJLoader();
loader.load("models/teaport.obj", function ( o ) {

var material = new THREE.MeshLambertMaterial(  );

o.traverse( function ( child ) {

    if ( child instanceof THREE.Mesh ) {

        child.material = material;
    }
} );
o.scale.set(50,50,50);
scene.add( o );

object = o; // <-- important

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

I can't seem to get the post method to work properly for some unknown reason

Hello there, I am encountering an issue while trying to submit a form on my website using the post method. For some reason, it keeps returning a null value. However, when I send data not through the form but instead by reading axios, it works perfectly fin ...

Is there a notification system that sparkles like a precious Facebook gem

Is there a system similar to Facebook's request, message, and notification bubble system that can alert users on their profiles about new messages or notifications? I know Facebook is very advanced, but if anyone knows of something similar, please let ...

What is the best way to send an ID to my ui-view component?

I am trying to access inventory items by their ID using the link /inventory/description/:{{id}}. However, I am facing some issues with it as nothing is showing up. How can I successfully access these items by ID? app.config(function config( $stateProvider ...

Express JS res.send() with an array response data is posing a concern during the Checkmarx scan

When using the axios library in my express middleware to retrieve responses from APIs, I encountered a security concern raised by Checkmarx scan report. router.post(someurl,req,res) { axios .get(someurl) .then((response=>{ **res.send(response.data);**/ ...

The Facebook Messenger chat widget appears to be malfunctioning and failing to

https://i.sstatic.net/SZPd9.png I've gone ahead and whitelisted the domains on our Facebook page, as well as generated the chat widget. However, despite disabling all content blockers, the code seems to have no visible effect on the page. Unfortunate ...

Retrieve a JSON array using an HTTP Get request in JavaScript (with jQuery)

I’ve been experimenting with various code snippets in an attempt to reach my objective, but so far I haven’t found a solution. Objective: My goal is to retrieve a JSON array of objects from a specific web URL using the GET method. This task needs to b ...

Efficiently updating database records without the need for page reloads using EJS

I'm working on a project that resembles the comment section on Reddit. Users can leave comments and others can reply to those comments. My tech stack includes Node, Express, MySQL, and EJS. The issue I'm facing is implementing the upvote/downvo ...

Extract data from JSON and append it to a new column within an already established CSV file

I am attempting to extract data from a JSON object (provided below) and insert it into a new column in an existing CSV file. Currently, when I run my code (also shown below), the only thing being added to the new column is the word "Array" repeatedly. How ...

React Navigation - CSS file identified as "text/html" after introducing a dynamic route parameter (/userId)

Our customized stylesheet "styles.css" seems to be incorrectly identified with the MIME type "text/html", even though it is specified as: rel="stylesheet" type="text/css" This issue only arises when navigating to routes with a variable parameter such as ...

Gathering Image Details

I am struggling to retrieve the information of a picture using this code snippet. The main issue I'm facing is accessing the link of the image. import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; im ...

What significance does it hold when an unhandled rejection event lacks a reason field?

Our app tracks client-side errors using Rollbar, but we keep encountering a not very helpful error message from Safari and Chrome: [unhandledrejection] error getting `reason` from event Upon investigation, I found that this message is generated by Rollbar ...

Activating two buttons in jquery will trigger this action

I am currently working on developing a filter button that will perform different actions based on which buttons are pressed. Pressing button1 will trigger one action, while pressing button2 will trigger another action. If button1 is pressed first, followe ...

Tips for capturing the datePicker closing event

Currently, I have successfully implemented a date picker on my website. In some sections of my page, there is a requirement for calculating values based on the start and end dates selected by the user. However, I am facing an issue where I am unable to per ...

Combining Json attributes in Jquery Grouping

My task is to group the displays by sectors, but I couldn't find a method in JSON to achieve this. Below is the code snippet: $(function displays(){ var url = '{% url get_displays %}'; $.getJSON(url, function(data) { var sidebar = ...

Can you explain the distinction between incorporating and excluding the keyword "await" in the following code snippets?

Currently, I'm diving into an MDN article that covers async/await. I've grasped the rationale behind using the async keyword preceding functions, yet there's a bit of uncertainty regarding the await keyword. Although I've researched "aw ...

The console correctly detects the value, but is unable to set the innerHTML property of null

I am currently working on a webpage that allows users to sign in and create an account. The issue I'm facing is that when I try to display the user's information, I encounter the error 'Cannot set property 'innerHTML' of null.&apos ...

Retrieve the data stored in a selection of checkbox fields on a form

I have a table of checkboxes: <div> <h1 class="text-center">Select activities</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Link activ ...

Utilizing NSURL for constructing new posts on a Rails server via JSON may involve redundant parameters

One problem I'm encountering is that when I make a POST request to a rails server to create a new post using code from the iPhone simulator, the parameters are being sent twice. NSDictionary *thestuff = [NSDictionary dictionaryWithObjectsAndKeys: ...

Parsing JSON Response in iOS using Swift and Alamofire

After receiving the JSON response from my server, this is what I found: { "case_details": { "status": "PENDING", "caseNumber": "ARBIT.CASE(C)/1/2017", "party": "COMBITHERM APPARATE-UND ANLAGENBAU GMBH .Vs. COXWELL DOMES ENGINEERS PVT. LTD. & ...

When querying the model, the result may be undefined

I'm encountering an issue where I can't access the content of an array of documents in my model and it's returning undefined. Here is the model structure (Project.js): var mongoose = require('moongoose'); var Schema = mongo ...