The acceleration of the ThreeJS scene intensifies with each passing moment

My friend and I have been collaborating on a university assignment - creating a basic Pacman clone using ThreeJS (which is a requirement). From the start, we've encountered a persistent issue. As our scene continues to run, it progressively speeds up with each passing second. Strangely, there isn't a decrease in the amount of content being rendered; everything remains consistent.

            import * as THREE from '././../three.js-master/build/three.module.js';

    function main() {
        const canvas = document.querySelector('#canva');
        const renderer = new THREE.WebGLRenderer({ canvas });
        renderer.setSize(window.innerWidth, window.innerHeight);

        /* Camera */
        const fov = 40;
        const aspect = window.innerWidth / window.innerHeight;
        const near = 0.1;
        const far = 1000;
        const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
        // The goal is to achieve an angled perspective that displays depth while keeping all significant elements visible
        camera.position.set(0, 65, -45); 
        camera.up.set(0, 0, 1);
        camera.lookAt(0, 0, 0);

        const scene = new THREE.Scene();

        /* Lights */
        const mainLight = new THREE.DirectionalLight(0xffffff, .85);
        mainLight.position.set(0, 20, 0);
        scene.add(mainLight);
        mainLight.castShadow = true;
        mainLight.shadow.mapSize.width = 2048;
        mainLight.shadow.mapSize.height = 2048;

        /* Additional code for board, player, enemies, collectibles, walls, points update, collision checking, etc.
           This section involves setting up various elements within the game environment */

        function render(time) {
           /* Rendering logic with resize handling, updating object positions, handling user input, rendering the scene, etc. */
        
            requestAnimationFrame(render);
        }

        requestAnimationFrame(render);
    }

    main();

Answer №1

Instead of repeatedly adding keypress event listeners during your render loop, consider initializing them once outside the loop. This will prevent multiple instances of the same listener from being created with each frame, which can cause your scene to speed up unnaturally over time.

By taking this approach, you should notice a decrease in the speed issue you are currently experiencing.

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

Examine every character in the text to determine if it qualifies as a separator

Can anyone assist me with a task I'm working on? I'm trying to write a function that checks the letters of a string. I attempted to use both a for loop and a foreach loop, but I couldn't get it to work properly :( let input = this.tagsFor ...

How to add vertical bars within ng-repeat in AngularJS

I attempted to retrieve values from an array variable using ng-repeat within unordered lists. Although the values are displaying correctly and everything is functioning properly, I added vertical bars after each value to represent sub-categories on my page ...

What causes the difference in behavior of nodejs function arguments when explicitly called?

As I refactor my nodejs application to improve code readability, I encountered an issue when calling a function directly. The following code works perfectly: router.route('/').get(({ query }, res, next) => { ItemsLogic.getItems(query) .the ...

When casting a ray from the inside, the raycast does not collide with the mesh

In my latest project, I've created a unique scene that involves placing my camera inside a sphere geometry. var mat = new THREE.MeshBasicMaterial({map: THREE.ImageUtils.loadTexture('0.jpg') , overdraw:true, color: 0xffffff, wireframe: fal ...

Preventing the need to reset JavaScript text inputs

I'm encountering a strange issue in my code. I'm developing a graphing calculator that requires users to enter multiple expressions for evaluation. I have a text input and a button that adds a new input to the parent div whenever it is clicked: d ...

Loop through with <li> inside a <td> tag

I need help figuring out how to place a list of items inside a table row using ng-repeat in AngularJS. Here is my attempted code: <td> <div ng-repeat="x in total.count"> ...

The current status of the Macrotask and Microtask queues as this calculation is being processed

This particular inquiry delves into a nuanced aspect of the event loop, seeking clarification through a concrete example. While it shares similar characteristics with another question on Stack Overflow, specifically Difference between microtask and macrota ...

Tips for saving variable state using closure

I am working on a function that needs to be called multiple times, and this function will add elements to my HTML: class MyClass { addElements(elements) { const parentElement = $("#parent").find("#other-element"); for (let element of elements) ...

Tips for using tooltip.format() to access an array of objects in anychart.js

Having difficulty displaying an array of objects in the tooltip of an Anychart.js map. I know we can access the dataset using %[name of property in data set]. The structure of my dataset is as follows: { "country": "Austria", &q ...

Tips on how to optimize form input mapping without losing focus on updates

I am facing an issue with a form that dynamically renders as a list of inputs. The code snippet looks like this: arrState.map((obj,index)=>{ return( <input type="text" value={obj} onChange{(e) => stateHandler(e,index)}<inpu ...

What is the most effective way to loop through HTML elements using wildcards in Puppeteer to extract innerText?

Seeking insights for educational purposes, I am in search of the reviews on this specific page . Each page contains 10 reviews, and I have a set of HTML selectors (previously used code) to extract these comments: #review_593124597 > div:nth-child(1) &g ...

The d3.select function is failing to update the chart on the website

I am facing a challenge in updating data in a d3 chart with the click on an HTML object #id. After successfully coding it in jsfiddle, I encountered issues when implementing it on a web page. The scenario involves a simple leaflet map where the chart is d ...

Tips on saving wavefront .obj models in mongodb

I need to save 3D models in .obj format into a MongoDB database. Would it be better to convert them to binary before storing? Any advice on how to tackle this situation would be highly valued. Thank you! ...

Trouble with executing two asynchronous AJAX calls simultaneously in ASP.NET using jQuery

When developing a web application in asp.net, I encountered an issue with using jQuery Ajax for some pages. The problem arose when making two asynchronous Ajax calls - instead of receiving the results one by one, they both appeared simultaneously after the ...

What are some effective troubleshooting methods for resolving issues with chrome.storage.sync?

My Chrome extension is a simple tool that utilizes the chrome.storage API to keep track of tasks in a organized list. Whenever there is an update to the task list, the array is saved to chrome.storage.sync. I have both of my laptops configured with the Ch ...

Tips for implementing a minimum character length feature in React Material-UI's Autocomplete feature

I am looking to add a 'minimum character length' feature to the autocomplete component in react material-ui. The code snippet below demonstrates what I have so far. constructor(props) { super(props); this.state = { // toggle for ma ...

Is it possible to retrieve AJAX data through a callback function?

I have encountered an issue where the ajax success function does not return data as expected. I attempted to use a callback function instead, but I still end up with undefined results. I resorted to using the variable responseText, however, I am looking fo ...

The text's worth in the code of javascript

Having an issue with my code where I want to add a string to my Confirm() function in JavaScript but it's not working correctly. myData.setValue(i, 9, '<a href="'+scriptDelete+'" onclick="return confirm();" > Delete </a>&ap ...

Utilize CamelCase in jQuery for Better Code Readability

Upon examining the jQuery source code, I noticed an interesting use of camelcase: camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } // where: rmsPrefix = /^-ms-/, rdashAlpha = /-([\da- ...

What is the best way to update the text on buttons once they've been clicked for a variety of buttons

I'm encountering an issue with multiple buttons where clicking on any button causes the text to change on the first button, rather than the one I actually clicked on. All buttons have the same id, and using different ids for each button seems impracti ...