Translocate an item using Three.js

onKeyboard: (event) => {
        let vars = Scene.vars;
        var vitesse = 0.5;
        var keyCode = event.which;
        if(keyCode ==37){
            vars.lambo.position.x += vitesse;
            vars.lambo.rotation.y += vitesse;
        }else if(keyCode == 39){
            vars.lambo.position.x -= vitesse;
            vars.lambo.rotation.y -= vitesse;
        }else if(keyCode == 40){
            vars.lambo.position.z -= vitesse;
        }else if(keyCode == 38){
            vars.lambo.position.z += vitesse;
        }

    }
Scene.loadFBX("Logo_Feelity.FBX", 10, [45, 22, 0], [0, 0, 0], 0xFFFFFF, 'logo', () => {
            Scene.loadFBX("Statuette.FBX", 10, [0, 0, 0], [0, 0, 0], 0xFFD700, 'statuette', () => {
                Scene.loadFBX("Socle_Partie1.FBX", 10, [0, 0, 0], [0, 0, 0], 0x1A1A1A, 'socle1', () => {
                    Scene.loadFBX("Socle_Partie2.FBX", 10, [0, 0, 0], [0, 0, 0], 0x1A1A1A, 'socle2', () => {
                        Scene.loadFBX("Plaquette.FBX", 10, [0, 4, 45], [0, 0, 0], 0xFFFFFF, 'plaquette', () => {
                            Scene.loadText(Scene.vars.text, 10, [0, 23, 52], [0, 0, 0], 0x1A1A1A, "texte", () => {
                                Scene.loadFBX("/Lamborginhi Aventador FBX/Lamborghini_Aventador.FBX", 10, [0, 0, 0], [0, 0, 0], 0xFFD700, 'voiture', () => {

                                    let vars = Scene.vars;

                                    let lambo = new THREE.Group();

                                    lambo.add(vars.voiture);
                                    lambo.position.set(0,0,200);
                                    lambo.scale.set(0.01,0.01,0.01);
                                    vars.scene.add(lambo);
                                    console.log(vars.scene.add(lambo))

                                    let gold = new THREE.Group();
                                    gold.add(vars.socle1);
                                    gold.add(vars.socle2);
                                    gold.add(vars.statuette);
                                    gold.add(vars.logo);
                                    gold.add(vars.texte);
                                    gold.add(vars.plaquette);

                                    let logo2 = vars.logo.clone();
                                    logo2.rotation.z = Math.PI;
                                    logo2.position.x = -45;
                                    vars.logo2 = logo2;
                                    gold.add(logo2);
                                    gold.position.z = -50;
                                    gold.position.y = 10;
                                    vars.scene.add(gold);
                                    vars.goldGroup = gold;

                                    let silver = gold.clone();
                                    silver.position.set(-200, 10, 0);
                                    silver.rotation.y = Math.PI / 4;
                                    silver.children[2].traverse(node => {
                                        if (node.isMesh) {
                                            node.material = new THREE.MeshStandardMaterial({
                                                color: new THREE.Color(0xC0C0C0),
                                                metalness: .6,
                                                roughness: .3
                                            })
                                        }
                                    });
                                    vars.scene.add(silver);
                                    vars.silverGroup = silver;

                                    let bronze = gold.clone();
                                    bronze.position.set(200, 10, 0);
                                    bronze.rotation.y = -Math.PI / 4;
                                    bronze.children[2].traverse(node => {
                                        if (node.isMesh) {
                                            node.material = new THREE.MeshStandardMaterial({
                                                color: new THREE.Color(0xCD7F32),
                                                metalness: .6,
                                                roughness: .3
                                            })
                                        }
                                    });
                                    vars.scene.add(bronze);
                                    vars.bronzeGroup = bronze;

                                    let elem = document.querySelector('#loading');
                                    elem.parentNode.removeChild(elem);
                                });
                            });
                        });
                    });
                });
            });
        });

        // ajout des controles
        vars.controls = new OrbitControls(vars.camera, vars.renderer.domElement);
        vars.controls.minDistance = 300;
        vars.controls.maxDistance = 600;
        vars.controls.minPolarAngle = Math.PI / 4;
        vars.controls.maxPolarAngle = Math.PI / 2;
        vars.controls.minAzimuthAngle = - Math.PI / 4;
        vars.controls.maxAzimuthAngle = Math.PI / 4;
        vars.controls.target.set(0, 100, 0);
        vars.controls.update();

        window.addEventListener('keydown', Scene.onKeyboard, false);
        window.addEventListener('resize', Scene.onWindowResize, false);
        window.addEventListener('mousemove', Scene.onMouseMove, false);

        vars.stats = new Stats();
        vars.container.appendChild(vars.stats.dom);

        Scene.animate();
    }

Hello all, I am currently working on a project using three.js for my class assignment. I have an object named "lambo" in the scene that I want to move with a function called "onKeyboard". However, when I try to move the object using this function, only the camera of the scene moves and I receive an error stating "Cannot read property 'position' of undefined" for statements like "vars.lambo.position.x += vitesse". I am looking for a solution to this issue, any help would be greatly appreciated. Thank you.

Answer №1

There appears to be a crucial line missing from your code:

vars.lambo = lambo;

By including this line, you can guarantee that vars.lambo is no longer undefined, allowing for successful access to its position property.

Answer №2

Accessing vars within your event handling function is restricted.

One workaround is to retrieve the variables directly from the Scene.

let vars = Scene.vars;

Alternatively, you can define vars as a global variable.

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

Create shorter nicknames for lengthy reference names within the ng-repeat loop

Is it possible to assign an alias to a long reference name in ng-repeat? Currently, I have 2 complex objects where one acts as a grouped index for the other. Although the ng-repeat template code is functioning correctly, it's getting hard to read and ...

Unexpected Behavior in ComponentDidMount

During my exploration of the React documentation, I came across an example of a clock timer implementation. It was interesting to see how the setInterval function is used inside the componentDidMount method to update the state and trigger re-rendering of ...

Modify one single object on the screen

I am currently using the three.js library for working with WebGL. In my project, I have two objects within the scene and I want to update them independently. I am utilizing shaders to alter the color of these objects and would like to adjust a uniform pa ...

Steps for displaying search results based on state when a button is clicked

My current challenge involves creating a component that displays a list of results upon clicking the "Find" button. However, I am encountering issues with the results state variable not resetting when I utilize setResults([]). In addition, only the most r ...

Developing a cube-shaped structure using CSS3DRenderer to mimic CubeGeometry functionality

Does anyone have a code example for creating a cube in ThreeJS using CSS3DRenderer? I am searching for a way to achieve something similar to the THREE.CubeGeometry but with the CSS3DRenderer. Here is an example of what I am trying to accomplish: var my_cu ...

Creating a virtual roulette wheel with JavaScript

I'm currently working on creating a roulette wheel using JavaScript. While researching, I came across this example: , but I wasn't satisfied with the aesthetics. Considering that my roulette will only have a few options, I was thinking of using ...

Change a function to disregard clicks initiated within the last cell of every row within a table

Currently, I have a JavaScript function in place that operates in the following manner. Upon clicking any row within the table, it leads to a new page at the link indicated on line 6. (The ID# from column 0 is appended to the end of the link). While this ...

Browser geolocation functions in version 1.6 (Gears) but unfortunately do not work in the newer version 2.0 (HTML5/W3C)

I ran tests on both emulator and real devices to confirm compatibility. To demonstrate geolocation capabilities, I created a mini experiment site at http://www.bctx.info/wx. It functioned flawlessly on my Android 1.6 (Magic, I/O Phone): requesting user pe ...

What is the CoffeeScript alternative for () => { return test() }?

Currently, I am attempting to write this code in CoffeeScript and finding myself at a standstill... this.helpers({ events: () => { return Events.find({}); } }); ...

Ways to categorize items using JQuery based on their hierarchical structure

I am looking to organize the following HTML content: <h2>State the Issue  </h2> <h3>Provide information about your objective</h3> <h3>Share any error messages received</h3> <h2>Outline Your Attempts  ...

Rotating the face normal in ThreeJS, just not specifically on the floor

I am currently working on developing a house generator using a floorplan. The mesh generation process is running smoothly, but now I am faced with the task of flipping the normals on certain faces. buildRoomMeshFromPoints(planeScalar, heightScalar){ va ...

Facing issues connecting to my MongoDB database as I keep encountering the error message "Server Selection Timed Out After 3000ms" on MongoDB Compass

I am encountering an error on my terminal that says: { message: 'connect ECONNREFUSED 127.0.0.1:27017', name: 'MongooseServerSelectionError', reason: TopologyDescription { type: 'Single', setName: null, maxS ...

Reasons why the intermediate state may not be visible to the user right after calling setState() in the componentDidMount() lifecycle method

While exploring the React Docs at https://reactjs.org/docs/react-component.html According to the documentation, it is stated that you may call setState() immediately in componentDidMount(). This action will result in an extra rendering, however, it will ...

Creating a custom JavaScript library using an existing npm module (codius)

Embarking on a new journey with this, never tried it before. Currently utilizing https://github.com/codius/codius-host. The development of Codiu§ has been abandoned, however I am determined to salvage some parts of it for my own project. It is crucial fo ...

Can you explain the significance of using curly braces in Javascript coding?

I came across the following code snippet on the page https://nodejs.org/api/modules.html: { }. Specifically, this line caught my attention: const { PI } = Math; Is there a specific term for this syntax? I'd like to learn more about it and understand ...

Believing that members possess a certain role when they actually do not

const { Discord, MessageEmbed } = require("discord.js"); module.exports = { name: "ban", description: "bans user from guild", execute(client, message, cmd, args, Discord) { const member = message.mentions.u ...

Set the value of this input element to its current value decreased by

I currently have several tabs with input fields on each tab. I have assigned the same class to each input field so that I can transfer values from one tab to another using the following code: $('.group_input1').change(function(){ $('.g ...

Iterate over the table data and present it in the form of a Google

I'm struggling to extract data from a table and display it in a google chart. I need some guidance on how to properly loop through the information. HTML <tr> <th>Date</th> <th>Score</th> <th>Result< ...

How can I dynamically insert rows and tables in AngularJS when a button is clicked?

I am looking to add functionality to my website where a table can have rows dynamically added upon clicking a button. Additionally, I want the ability to re-create and display the table on the page with another button click. Below is the HTML code I have ...

Internet Explorer 6 doesn't allow for DOM manipulation of the created combobox in Ajax time

When making an async request on a website, the response is parsed into a select field where the option gets selected once the DOM nodes are ready. This process works perfectly on all browsers except for Internet Explorer 6, which presents some strange beha ...