Attempting to retrieve the parameters of a function from a nested function

Currently, I am utilizing three.js alongside a script similar to OrbitControls as my controller. Within my main.js file, I am passing a THREE.Group() to the controller as an argument with the intention of rotating the entire group.
Issue 1: Once the group is delivered to the controller, accessing its properties directly becomes problematic without creating a duplicate.
Issue 2: The duplicate fails to encompass the complete THREE.Group(), but instead only retains the initial child.

After extensively working on this task for hours and experimenting with around 50 different solutions, including various resources on stackoverflow, I am at a loss for how to address this predicament.

main.js

let container;
let camera; 
let controls;
let game;
let renderer;
let scene;

function init() {
    container = document.querySelector('#scene-container');
    scene = new THREE.Scene();

    const fov = 35;
    const aspect = container.clientWidth / container.clientHeight;
    const near = 0.1;
    const far = 100;
    camera = new THREE.PerspectiveCamera(fov, aspect, near, far);

  //***** This is the important line ******
    controls = new THREE.ObjectControls(camera, container, game);

    game = new THREE.Group();
    scene.add(game);

    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial();

    var mesh1 = new THREE.Mesh(geometry, material);
    game.add(mesh1);
    var mesh2 = new THREE.Mesh(geometry, material);
    mesh2.position.set(0,1,0);
    game.add(mesh2);

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(container.clientWidth, container.clientHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
    container.appendChild(renderer.domElement);

    renderer.setAnimationLoop(() => {
        renderer.render(scene, camera);
    });
}

init();

ObjectControls.js

THREE.ObjectControls = function (camera, domElement, objectToMove) {
    mesh = objectToMove;
    domElement.addEventListener('mousemove', mouseMove, false);

    function mouseMove(e) {
        //** objectToMove is undefined :( **
        mesh.rotation.y += 3;        
    }
};

The expected outcome is to rotate the entire THREE.Group() game, yet the current result only rotates the first child within game, in this instance mesh1.

Answer №1

objectControls = new THREE.ObjectControls(camera, container, game);
game = new THREE.Group();

Your code contains an error where you are passing the undefined variable `game` to the constructor of `ObjectControls`. If you assign a new object to `game` on the next line, `ObjectControls` will not have a reference to this variable.

To fix this, make sure to assign the group object to `game` first and then create the instance of `ObjectControls`. Simply switch the order of these two lines in your code.

Using three.js version R105

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

Is it possible to display data on a webpage without using dynamic content, or do I need to rely on JavaScript

Imagine a scenario where I have a single-page website and I want to optimize the loading time by only displaying content below the fold when the user clicks on a link to access it. However, I don't want users with disabled JavaScript to miss out on th ...

Trouble with document updates in MongoDB/Mongoose causing a delay?

I am currently working on updating an object nested in an array in my application. When I test this functionality using Postman, I am experiencing a delay that requires me to make two requests in order to see the updated value. if (taskStatus) { cons ...

Having trouble with the response from the Object object?

Can someone assist me with the response I am getting here? I am receiving a response from an API call and trying to store the results from screen_results. However, when I attempt to print it out, all I see is [Object object]. I have tried to stringify it, ...

What is the process for incorporating a compiled JavaScript library into a TypeScript project?

In my Typescript project (ProjectA), I am utilizing several node packages. Additionally, I have a babel project (ProjectB) with a build configuration that supports output for multiple module definition standards such as amd, common.js, and esm. My questio ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

"Exploring the Power of Angular Change Detection with Promises in a Hybrid

We are currently in the process of upgrading an AngularJS project to Angular 7 by following the recommended "hybrid" approach where both frameworks coexist. However, we have encountered some issues with change detection when dealing with native promises. T ...

AngularJS fetches the 'compiled HTML'

If I have this angularjs DOM structure <div ng-init="isRed = true" ng-class="{'red': isRed == true, 'black': isRed == false}"> ... content </div> How can I obtain the 'compiled' version of this on a cl ...

The value of ng-model is consistently stored as a string, regardless of whether the input is a number or

<div> <input type="text" ng-model="test"/> </div> When a value is entered into the input field with the ng-model "test", it is always treated as a String type, even if it is a valid number. However, I am looking for a way to determine th ...

Implement scroll bar functionality on canvas following the initial loading phase

I am currently working with canvas and I need to implement a scroll bar only when it is necessary. Initially, when the page loads, there isn't enough content to require a scroll bar. My project involves creating a binary search tree visualizer where u ...

Error encountered when uploading files using Multer (Node.js and React)

I've just submitted a request from the client, and it seems to be causing some issues. Here's the code snippet that is giving me trouble: if(file){ const data = new FormData() const fileName = Date.now() + file.name data.append( ...

Remove an object based on its unique identifier with the help of mongoose

I am working on developing an API to delete a document in MongoDB using Mongoose. Below is the route I have created: router .route("/tasks") .delete('/:id', function (res, err) { taskSchema.findByIdAndRemove(req.params.id, (err, ...

What steps do I need to follow to execute React/Next code that I have downloaded from GitHub?

I recently obtained a zip file from https://github.com/prgrms-web-devcourse/Team_Price_Offer_FE and extracted its contents. When attempting to launch the program in Visual Studio Code, I inputted the command npm start but encountered an issue. Team_Price_ ...

Protractor troubleshooting: Issues preventing execution of protractor tests

My tests suddenly started throwing an error. Everything was working fine before this. Any advice on how to fix it? Here is my Config file: exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', allScriptsTimeout: 20000, baseU ...

Is there a way to navigate by scrolling, moving a centrally-positioned SVG along a path while also resizing the SVG?

After following the instructions in this post about resizing SVGs, I managed to keep the red square on the path while resizing the SVG. However, a new issue arises when scrolling down - the red square is not moving to stay positioned at the center of the w ...

What is the best way to manage variables that are not present in a Vue.js template?

When working with vue.js templates, I often come across instances like this: {{ jobs[0].stages[0].node.name }} If a job has no stages, the entire template fails to load and vue.js admin throws this warning: Error in render: "TypeError: Cannot read prope ...

Tips on capturing the response data in UI testing automation

Currently, I am working on automating a login page using WebDriverIO for UI Automation. After clicking the Login button, a request to *.com/user/login is triggered in the background. I need to capture this call's response in order to obtain a token r ...

Issue encountered: "An error has occurred stating that your cache folder contains files owned by root. This is likely a result of a bug present in older versions of npm. This issue arose during the execution of the

While attempting to create a new react app using the command npx create-react-app example_app, I encountered the following issue: [ Your cache folder contains root-owned files, due to a bug in previous versions of npm which has since been addressed sudo ...

Is it possible to generate an error if you attempt to retrieve a property that does not exist within a JavaScript object?

I am creating a new object with specific properties. I need to ensure that an error is triggered if the user attempts to retrieve a property that doesn't actually exist. Is there a way to achieve this in my code? ...

Enhancing the Efficiency of JavaScript's indexOf Method

I am currently developing a basic search algorithm in JavaScript. var title = "Discovering the Best Book of All Time"; var search1 = "of DiscoverinG boOk Best"; var search2 = "Of TIme best all" var search3 = "Book discovering time" When using indexOf(), ...

Concealed checkbox value in jQuery

I have a problem with setting the hidden checkbox "marketingPhone" to TRUE when the "marketingAAA" checkbox is checked as true. This part works fine. However, if any other checkbox on the page is set to TRUE, then it also sets "marketingPhone" to TRUE. I ...