The importedMesh function in babylonjs does not have a return value and will

I've been working with BabylonJS and recently imported a Mesh from Blender.

However, I encountered an issue at this line :

         x = this.cube.position.x;

It resulted in

Uncaught TypeError: Cannot read property 'position' of undefined

Below is the complete code :

export class Game {
private canvas: HTMLCanvasElement;
private engine: BABYLON.Engine;
private scene: BABYLON.Scene;
private camera: BABYLON.FreeCamera;
private light: BABYLON.Light;
private skybox: BABYLON.Mesh;
private skyboxMaterial: BABYLON.StandardMaterial;
private waterMesh: BABYLON.Mesh;
private water: Materials.WaterMaterial;
private ground: BABYLON.Mesh;
private groundTexture: BABYLON.Texture;
private groundMaterial: BABYLON.StandardMaterial;
private sphere: BABYLON.Mesh;
private sphereMaterial: BABYLON.StandardMaterial;
private cube: BABYLON.Mesh;


constructor(canvasElement : string) {
    // Create canvas and engine.
    this.canvas = document.getElementById(canvasElement) as HTMLCanvasElement;
    this.engine = new BABYLON.Engine(this.canvas, true);
}

createScene() : void {
    this.scene = new BABYLON.Scene(this.engine);

    this.camera = new BABYLON.FreeCamera("Camera", BABYLON.Vector3.Zero(), this.scene);
    this.camera.attachControl(this.canvas, true);


    this.light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), this.scene);

    // Skybox
    this.skybox = BABYLON.Mesh.CreateBox("skyBox", 1000.0, this.scene);
    this.skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this.scene);

...

....

        };

        ////////// RAY CAST TO FIND WATER HEIGHT ////////////

...

doRender() : void {
    // Run the render loop.
    this.engine.runRenderLoop(() => {
        this.scene.render();
    });

    // The canvas/window resize event handler.
    window.addEventListener('resize', () => {
        this.engine.resize();
    });
}

While I understand that adding a null check can resolve the error, I find it puzzling why my cube is undefined when using (ImportMesh) which is supposed to be a Synched function.

Implementing a null check resolved the error for me.

Answer №1

When loading bue asynchronously using the ImportMesh function, it may not be available in the initial frames. This can result in an exception being thrown in your registerBeforeRender function. To address this issue, consider the following:

    this.scene.registerBeforeRender(function() {
        let time = this.water._lastTime / 100000;
        let x = this.sphere.position.x;
        let z = this.sphere.position.z;
        this.sphere.position.y = Math.abs((Math.sin(((x / 0.05) + time * this.water.waveSpeed)) * this.water.waveHeight * this.water.windDirection.x * 5.0) + (Math.cos(((z / 0.05) +  time * this.water.waveSpeed)) * this.water.waveHeight * this.water.windDirection.y * 5.0));

        if(this.cube) {
          x = this.cube.position.x;
          z = this.cube.position.z;
          this.cube.position.y = Math.abs((Math.sin(((x / 0.05) + time * this.water.waveSpeed)) * this.water.waveHeight * this.water.windDirection.x * 5.0) + (Math.cos(((z / 0.05) +  time * this.water.waveSpeed)) * this.water.waveHeight * this.water.windDirection.y * 5.0));
        }

    }.bind(this));

One simple solution is to register the before-Render function after ensuring the cube is loaded (in the onSuccess callback of ImportMesh)

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

Ways to repair the mouse hover transform scale effect (animation included)

I am currently facing an issue with my GridView that contains images. When I hover over the top of the image, it displays correctly, but when I move to the bottom, it does not show up. After some investigation, I suspect that there may be an overlay being ...

Switching Between Background Images in Angular

Looking to change the background-image of an element upon clicking it. Currently, this is what's in place: <div class="item-center text-center" toggle-class="active cable"> <div class="quiz-background"></div> <p class="size ...

JavaScript validation is failing to return false when re-entering the password

My JavaScript validation code is working fine. Javascript: All fields return false when re-entering the password, but JavaScript does not return false if it's not working The Re-Enter password JavaScript code is failing to work... An alert is displ ...

Issue with OnChange event in HTML and Adding Content with Jquery

I'm currently working on an app that includes a dynamic dropdown feature using jQuery and the append() method to display changing numbers dynamically. Everything seems to be functioning well in the first field of the form, but when I try to add more f ...

Is the RequireJS jQuery plugin shim failing to function properly?

Currently, I am facing a challenge in getting a jQuery plugin to function properly with RequireJS. My aim is to use jQuery in the noconflict/noglobal state to ensure that all modules clearly indicate if they require jQuery. However, I have encountered issu ...

Tips for modifying a particular element within a class?

I am seeking guidance on how to modify a specific class attribute in CSS/JS/JQuery when hovering over a different element. Here is an example: <h1 class="result">Lorium</h1> <h1 class="result">Ipsum</h1> <h1 class="result">Do ...

Using RegEXP in Javascript, you can easily eliminate characters that fall between two special characters without removing the special characters

I'm facing an issue with a string that looks like this: var str = "1111 type reallycoolsentence\text.json\n1111 type anotherreallycoolsentence text2.json My goal is to eliminate the characters located between the backslashes in the str ...

Selenium Intern issue: ERROR - suiteEnd message received for session that does not exist

I have been attempting to set up functional testing using Intern 4 with a headless Chrome browser. I have installed selenium-server-standalone on my Mac terminal and believe everything is configured correctly. However, when I try to run the test, I encount ...

Executing commands in the console using Playwright JS testing

We are looking to execute the command '$gui.dispatch('callBarcodeHandler', '98783083')' in the console during testing. An example scenario would be logging in and needing to send a command to scan a barcode. ...

Craft an engaging and dynamic Image map with SVG technology to elevate responsiveness and interactivity

I'm currently working on a website and I need to create two clickable sections on the home page. Each section will lead to a different specialization of the company. To achieve this, I decided to use a square image split into two right-angled triangle ...

Tips for creating a two-tier selection filter system

I'm having an issue with this code. My objective is to create two filters for this table. The select element with id="myInput" should determine which rows appear in the table and apply the first filter. Here is the JavaScript code: function myFunctio ...

Is it possible to save an array as a string in a MySQL database?

Is this considered a good practice? I am planning to save bookmarks, with each bookmark being stored as a row in the table. I intend to have a tag column that will essentially be an array in string format holding the hierarchy of tags defining it. For ins ...

What is the behavior of the JavaScript event loop when a Promise's resolution is tied to setTimeout?

console.log('1') setTimeout(() => { console.log('2') }, 0) function three() { return new Promise(resolve => { setTimeout(() => { return new Promise(resolve => resolve('3')) },0) ...

Trouble with displaying a CSS background image in Google Chrome on the Three.js birds demo

My website displays a background image in both Safari and Firefox, but for some reason Google Chrome is not showing it. I am unsure why this is happening. Do you have any insights on what I might need to adjust? renderer = new THREE.CanvasRenderer(); ren ...

Can JSON files be used to store arrays with multiple dimensions?

I'm attempting to save a "multidimensional array" in a json file that will be used in JavaScript, essentially an array containing multiple arrays. Is this doable? If so, how can I achieve it? I tried formatting it the same way as in JavaScript, but it ...

Dealing with the Windows authentication popup in Protractor

I recently started using Protractor and encountered a problem with managing the authentication popup. I have included a screenshot for reference. If anyone has a solution, please advise me on how to resolve this issue. Thank you in advance. ...

Converting HTML input to a file using JavaScript

Here is the React.js component code I'm working with: import React, {ChangeEvent, useState} from "react"; import { Button } from "@mui/material"; function UploadCVButton() { const [selectedFile, setSelectedFile] = useState(null ...

What is the best way to implement Angular 8's version of jQuery's ajax functionality?

I am in the process of transitioning from basic HTML and JavaScript to Angular for my web application. This means I need to rewrite my JavaScript Ajax calls to my PHP server controller in Angular syntax. As a beginner in writing Ajax calls with jQuery and ...

Passing attributes to a pre-loaded component with next/link

import TestAcademy from './test-academy.js'; function MyApp({ Component, pageProps }) { const router = useRouter() const [approved, setApproved] = useState(false) ... return( <Link href='/test-academy' ...

Incorporating Jest alongside setTimeout and leveraging useFakeTimers

As I work with a TypeScript async function that requires a 1-second sleep between two statements, this implementation is in place: async function systemUnderTest(): Promise<void> { console.log("One"); await new Promise(r => { set ...