Can enemies in Javascript's EaselJS library execute the same functions simultaneously?

Hey everyone!

I've been working on creating a dodge game using JavaScript.

I have a question about how to ensure that each of the 3 enemies I create will have unique functions. Right now, they all move in the same direction determined by enemyrandom1(). How can I make them separate and independent?

Here's the code I'm using to create the enemies:

var item;
var enemy;
var enemys = new Array();

function createEnemy(){
    enemy = new createjs.Shape();
    enemy.graphics.beginFill("black").drawRect(0, 0, 10, 10);
    enemy.x = (Math.random() * 400) + 1;
    enemy.y = 50;
    stage.addChild(enemy);
    enemys.push(enemy);
    console.log(enemys);
}

createEnemy();
createEnemy();
createEnemy();

function enemyforloop(){
    for(var i=0; i<enemys.length; i++) {
        item = enemys[i];
        enemyMove();
    }
}

The enemyforloop is included in the Ticker method. The function enemyMove() is responsible for moving the enemies and placing them in random positions once they reach a certain point.

function enemyMove(){
    if(enemyrandom == 1){
        item.y -= enemyspeed;   
        if(item.y < -10){
            enemyrandom1();
        }
    }
}

function enemyrandom1(){
    enemyrandom = Math.floor((Math.random() * 4) + 1);
    enemyspeed = Math.random() * 2 + 1;

    if(enemyrandom == 1){
        item.y = 300;
        item.x = Math.floor((Math.random() * 400) + 1);     
    }
}

I didn't include enemyrandom and enemymove 2, 3, 4 to keep it concise. I hope my question was clear enough.

You can see the current version of the game here: http://jsfiddle.net/HqYeD/411/

Answer №1

To improve efficiency, it is recommended to eliminate the global variables enemyspeed and enemyrandom, and instead assign them within the scope of each individual enemy.

function createEnemy() {
    enemy = new createjs.Shape();
    enemy.graphics.beginFill("black").drawRect(0, 0, 10, 10);
    enemy.x = (Math.random() * 400) +1;
    enemy.y = 5;

    // Assign direction and speed specific to each enemy
    enemy.enemyspeed = Math.random() * 2 + 1;
    enemy.enemyrandom = Math.floor((Math.random() * 4) + 1);

    stage.addChild(enemy);
    enemys.push(enemy);
    console.log(enemys)
}

Your code should be adjusted accordingly...

function enemyMove() {
    if(item.enemyrandom == 1) {  
        item.y -= item.enemyspeed;   
        if(item.y < -10)
        {
            enemyrandom1();
        }
    }
  // ....
 }

And also...

function enemyrandom1() {

    item.enemyrandom = Math.floor((Math.random() * 4) + 1);
    item.enemyspeed = Math.random() * 2 + 1;

    if(item.enemyrandom == 1){
        item.y = 300;
        item.x = Math.floor((Math.random() * 400) + 1);     
    }
    // ....
}

Answer №2

Your “item” variable is currently scoped globally, just like the “enemy” in your initial example on the CreateJS community forum. This setup is causing issues for you because both variables are accessible throughout your entire program.

To resolve this issue, it’s recommended to declare the item variable inside the function and pass it into the “enemyMove” method like so:

function enemyforloop(){
    for(var i=0;i<enemys.length;i++) {
        var item = enemys[i]; // Define item within the loop
        enemyMove(item); // Pass item into enemyMove
    }
}
function enemyMove(item){
    // No changes needed here
}

Please ensure that you remove the global declaration of “var item” at the top of your script. Variables that are only used temporarily should be declared inside functions like we did with item. Both “enemy” and “item” objects are constantly changing, making them transient and unsuitable for global scope.

I hope this clarifies things for you!

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

Why Angular ng-repeat does not bind or display any values in Twig template

I am encountering difficulties while starting my new Angular project. Initially, I have a controller named DashCtrl in a module called sandpiper, with plans to divide it into services later on. The goal is to create a list of div.card elements from the $s ...

Transforming varied JavaScript objects into a serial form

In my application, there is a concept of an interface along with multiple objects that implement this interface in various ways. These objects are created using different factory methods, with the potential for more factories to be added as the application ...

Autocomplete Dropdown failing to select default value when defaultValue option is set

stateNPAValue[formData.state.vale] = 0: "All",1: "959", 2: "203",3: "860", 4: "475" // API response for NPA data const [selectedNamesState, setSelectedNamesState] = useState([]); const transformedNpaData ...

What's the best way to integrate Bootstrap into my HTML document?

Hey there, I'm new to the coding world and just started learning. I could use some assistance with including Bootstrap v5.1 in my HTML code. The online course I'm taking is using an older version of Bootstrap, so I'm having trouble finding t ...

Identifying the Operating System of Your Device: iOS, Android or Desktop

I am in need of displaying different app download links based on the user's operating system. This includes IOS, Android, or both if the user is accessing the page on a Desktop device. I am currently utilizing React and Next.js for this project. Unfor ...

How to add an hr tag to a div element in HTML dynamically with JavaScript?

Whenever a user interacts with the search box, I have a list that gets populated. Here is an example of the overall structure: <div id="searchResult"> <div> <a href="#">result1</a> </div> <div> <a href="#">result2 ...

Storing a JavaScript variable into a JSON file to preserve data

Is it possible to save data from variables to a JSON file? var json_object = {"test":"Hello"} $.ajax({ url: "save.php", data: json_object, dataType: 'json', type: 'POST', success: ...

Enhance the readability of your Angular/Ionic applications with proper hyphenation

In my Ionic 3 app, I am using an ion-grid. Some words do not fit within the columns and are cut off, continuing on the next row without any hyphens added for proper grammar context. See image https://i.stack.imgur.com/3Q9FX.png. This layout appears quite ...

Android params not being transferred to Node.js properly when using Volley

I am currently developing an application that utilizes several node.js scripts for server scripting primarily due to node.js's built-in Firebase support. However, I have encountered an issue where I am unable to send any parameters with my requests, w ...

Tips for utilizing the console.log function to extract a targeted value within nested objects

const businessDetails = { owner: { fullName: "Fred Stone", position: "Chief Technology Officer", company: "Software Solutions", }, employees: [ { fullName: "Pete Perkins", department ...

The REACT- Popover feature seems to be having trouble showing the data from my json file

Within the menu/ section, the names of my invited guests are not visible; only the InfoIcon is displayed in the cell. My goal is to implement a Popover feature that will show all the information about the invited guests (including their names and locations ...

How to generate a two-dimensional array in Spark using PySpark

Utilizing Python 2.7 within Spark, I am faced with two lists of 2-dimensional points. The first list, A, contains n points while the second list, B, contains m points. Each point is denoted by a pair of coordinates (x and y): set_a = [[x1, y1], [x2, y2], ...

Numerous JavaScript modules incorporated within Ember.js

I am in the process of creating a prototype Single Page Application using Ember.js. To speed up development, I am currently utilizing three separate JavaScript components: a calendar/todo list, a JavaScript clock, and a jQuery plugin. My goal is to have th ...

Animating images on scroll using Bootstrap's utilities

Is it possible to use bootstrap for creating a responsive animation of a bicycle moving from start to end as the user scrolls down the page? Additionally, how can I incorporate a responsive dotted line using bootstrap as well? Are there any codepen exampl ...

Struggling with converting 11-line toy neural network code into JavaScript

I'm preparing to deliver a brief presentation on neural networks this coming Tuesday to my fellow web developer students. My plan was to convert this code (found under Part 1, a tiny toy neural network: 2 layer network) into JavaScript so that it woul ...

Issues with Angular ngroute: controllers are not functioning properly

In order to route my application with different themes on the same page, I plan to utilize the ngroute module. Here's an example of how I intend to achieve this: <html> <head> <title>Angular JS Views</title> ...

The chat message section is failing to update due to AJAX not refreshing

I recently launched a new website and am facing challenges with the chat feature. Despite using ajax to update the chat messages without refreshing the page, the other user still needs to refresh in order to see the latest message. We are both in the sam ...

Utilize a traditional JavaScript class to instantiate an object in Vue.js

Is it possible to integrate a standard JavaScript class into a Vue.js component without needing anything static? If not, I am open to switching to React or Angular. Are they more suitable than Vue.js for code reusability? Test.js file: class Test { co ...

Using Excel VBA to extract data from a JSON string and populate cells with the corresponding key:value pairs

I am facing a dilemma with my Excel spreadsheet setup which includes columns: | A | B | C | D | | Job number | Status | Actual Hrs | % Complete | 1___|____________|________|____________|____________| 2___|___________ ...

What causes my slider to speed up with an increase in items and slow down with fewer items in bxslider?

Find more information here jQuery('.homepage_slider').bxSlider( { minSlides: 1, maxSlides: 4, slideWidth: 200, slideMargin: 30, ...