Using SetTimeOut in THREE JS

I'm currently working on a project for my master's degree that involves creating a space invaders game using three.js.

While the project is progressing well, I've encountered a problem with my aliens (THREE.Mesh object) being able to fire randomly. I've created a function that successfully generates a random number for this purpose. However, I'm facing an issue with the animate() function. I'm unable to use SetTimeout() within the animate() function.

The SetTimeout() function works the first time animate() is called, but afterward, there is no delay. The code continues to execute without waiting for the timer.

I suspect the problem may be due to animate being constantly called by requestAnimationFrame().

Here's a snippet of my code:

Index.html =>

if (!init()) animate();

function animate(){
   requestAnimationFrame(animate);
   level1.animate();

   render();
}

Level.js =>

Level.prototype.animate = function()
{

//Timer doesn't work
var that = this;

//Just a test with a simple console.log test
setTimeout(function() { console.log("test"); }, 10000);

this.sky.rotation.x -=0.005;

this.spaceship.fire();
for (var i = 0; i < this.ducks.length; i++)
{
   this.ducks[i].move();
    if (this.ducks[i].is_ready_to_fire())
        this.ducks[i].fire_if_ready();
}

};

With this code, the program will wait 10 seconds before printing "test" the first time, but subsequently, it will print "test" without any delay.

Do you have any suggestions on how to fix this issue?

Thank you for your help.

Apologies for any language barriers.

Answer №1

Do you require a timer for your specific purpose?

If I have understood your issue correctly, you are looking to have the aliens fire after a random delay.

If the exact timing is not crucial and you just want the aliens to shoot at random intervals, you can implement a frame counter for each alien to track when it should fire.

Here is a sample code snippet to illustrate this:

var MAX_FRAMES_TO_WAIT = 600000;

Alien.prototype.init = function() {
 this.framesUntilFire = Math.round(Math.random() * MAX_FRAMES_TO_WAIT);
}

Alien.prototype.fireWhenReady = function() {
  if(--this.framesUntilFire === 0) {
    this.fire();
    this.framesUntilFire = Math.round(Math.random() * MAX_FRAMES_TO_WAIT);
  }
}

function animate() {
  requestAnimationFrame(animate);

  /* ... */

  for (var i=0; i<this.ducks.length;i++)
  {
    this.ducks[i].move();
    this.ducks[i].fireWhenReady();
  }

This approach should work for you. Just keep in mind that the alien firing rate will be affected by the frame rate of the game.

You can address this by also calculating the frame rate and using it to adjust the firing rate.

I hope this information was helpful to you!

Answer №2

To prevent setting a new timer on each frame, you can opt to reset the timer once the previous one completes. An effective approach to achieve this is by using recursion:

function delayFire() {
    setTimeout(function() {
        if (!currentLevel) {
            return;
        }

        delayFire();
        fire();
    }, Math.random() * 1000);
}

This recursive function will cease firing if the level is no longer the active level.

Do you follow that logic?

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

Fetching JSON Data from Web Service using Ajax URL Field - A Simple Guide

I'm facing an issue while attempting to retrieve JSON Data from a web service using ajax url. This is how I have coded it so far: <script type="text/javascript> $('#kategoriTable').dataTable({ ajax: { u ...

Adding elements to the <Head> section in Next.js

I am facing an issue where I need to change the page title dynamically based on the route of the web pages. I have been assigned the task of creating and importing a title component into the layout file, but despite my efforts, nothing seems to change. con ...

Express Producing Empty Axios Post Request Body

I am facing an issue with sending two text data pieces from my React frontend to an Express backend. Whenever I use the post command with Axios, the body appears as {} in the backend and becomes unusable. Below is the code that I am using. Client (App.js) ...

Transferring a selection from a dropdown menu

I am currently working on a dropdown menu where each entry has an ID and a value. The issue I am facing is that when I click on an item on the list, the click-handler is called and passes the div. While the click handler can access the id without any probl ...

Tips for returning JSON data using AJAX

When working with native JS, I am familiar with using AJAX to display the output from PHP/mySql that is not Json Encoded in the element "some_id" like this: <script> function addItem(value) { xmlhttp = new XMLHttpRequest(); xmlhttp.onrea ...

In Angular, the ng-click directive that assigns the value of tab to $index does not seem to be functioning properly

I encountered an issue within my app <li ng-repeat="name in tabs track by $index" ng-class="{selected: tab==$index}" ng-click="tab = $index">{{name}}</li> After clicking on each item, the selected class remains enabled and switching to anothe ...

Issue encountered when attempting to generate a mongoose schema using a JSON document

Can I define this JSON file structure as a mongoose schema? Mongoose lacks an object type, and I'm unsure how to proceed with it. { "Moutainbike": { "Cross": { "size": [ "395 mm", "440 mm", "480 mm", "535 mm" ], "color" ...

Developing a matrix arithmetic parser using JavaScript

Currently, I am in the process of developing a program that can solve matrix equations. My main focus right now is on making sure the parser functions correctly. However, I am feeling lost and unsure of where to begin. In my program, I utilize an array of ...

What is the process for integrating a gltf model into Aframe & AR.js with an alpha channel?

--Latest Update-- I've included this code and it appears to have made a difference. The glass is now clear, but still quite dark. Note: I'm new to WebAR (and coding in general).... but I've spent days researching online to solve this issue. ...

Is there a way to store a complete array within a single cell?

I am searching for a solution to assign an entire array to a cell in Google Apps Script and Google Sheets. My attempt at using cell.setValue(array) only resulted in the cell containing the first item of the array. var cell = SpreadsheetApp.getActiveSprea ...

Can someone please provide me with a Javascript code snippet that accomplishes the same function

<script> document.addEventListener('DOMContentLoaded', function () { const menuItems = document.querySelectorAll('.headmenu li'); menuItems.forEach(function (menuItem) { menuItem.addEventL ...

Oh no, there seems to be an issue with accessing the 'map' property in REACT JS. It appears to

Upon attempting to delete an item, I encountered an error message stating "cannot read notes, property of undefined". Despite this issue, the map function seems to be functioning as expected. It is my belief that there may be an error within the filter fun ...

Using JavaScript to load the contents of a JSON file

I attempted to display data from a JSON file on an HTML page using jQuery / Javascript. However, each time I load the page, it remains blank. Below is the code snippet: index.html <!DOCTYPE html> <html> <head> <meta conten ...

What steps can be taken to ensure a function operates even when the mouse is stationary?

$(document).ready(function() { var score = 0; $("body").mousemove(function() { score++; $("#result").val(score); console.log(score); }); }); As I move my mouse, the score keeps increasing. But, I'm wonde ...

Vue.js is displaying the error message "Expected Object, got Array" when the length appears as undefined

I have an app where users input style codes into a field. I want to create a popup confirmation modal that displays a message with the number of style codes provided. The code I currently have is: <template> <h4>Style Number</h4> <For ...

Retrieve information from D3 line interpolation functions

I'm currently working on creating a D3 graph that features a shaded area in the middle. The top part of the shaded region aligns with the line graph. For reference, the data structure I'm using is as follows: line = [ {x: 0, y:1}, {x: 1, y: ...

Checking JavaScript files with TSLint

After spending many hours attempting to make this work, I still haven't had any success... I am wondering: How can I utilize TSLint for a .js file? The reason behind this is my effort to create the best possible IDE for developing numerous JavaScrip ...

Obtain the beginning and ending positions of a substring within a larger string

As a beginner in the world of AngularJS and web development, I am faced with a challenge. I have a specific string that is currently selected on a tab, like so: var getSelectedText = function() { var text = ""; if (typeof window.getSelection !== "un ...

The key property is present on the list item, yet the key warning persists

I have encountered various issues with this problem, but I am unable to pinpoint the exact cause. I am not extracting individual list items and simply displaying a UL with unique keys assigned to each item. However, when I log the results, I see something ...

Is it possible to simultaneously wait for the completion of two methods instead of awaiting each one individually?

When dealing with 2 async methods, one may want to run them simultaneously but wait for both to finish before proceeding. Here is an example: exports.get = async id => { const part1 = await context.get(id); const part2 = await context.get2(id ...