# Using array of images to spawn enemies in game

**URL:** <https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341>\
**Category:** Beginners\
**Created:** [April 24, 2024, 11:19am UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341 "2024-04-24T11:19:08Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![dsdsdsds](https://avatars.discourse-cdn.com/v4/letter/d/9f8e36/32.png) [@dsdsdsds](https://discourse.processing.org/u/dsdsdsds)\
**Post date:** [April 24, 2024, 11:19am UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/1 "2024-04-24T11:19:08Z")

</div>

Hi,

I’m new to Processing and I’m trying to create a part of the game where enemies appear on the left side of the screen and move towards the right side of the screen in a 5 second interval. I’m using an array of images, and each time I want the code to randomise:

1. Which image out of the array is spawned  
and
2. The y co-ordinate of the image

I’m not sure where to start. Any guidance would be greatly appreciated.

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [April 24, 2024, 11:45am UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/2 "2024-04-24T11:45:44Z")

</div>

Hello @dsdsdsds,

> [@dsdsdsds](#):
>
> I’m not sure where to start. Any guidance would be greatly appreciated.

A good place to start:

> [@Guidelines—Asking Questions](https://discourse.processing.org/t/guidelines-asking-questions/2147):
>
> Summary (TL;DR) Ask complete questions to get better answers! Be specific. For example: I want to load an image. I tried using createImg() , and I expected the image to be on canvas, but what happened instead was the image showing up below the canvas. Isolate your problem and work in small steps. Share only the code directly related to your problem if it is part of a bigger project, and if something isn’t working, try the smallest code that could do the thing you want. Can we run your code to …

Break down what is required first:

1. Array of images \< Assuming you have already done this.
2. Access a random element of the array.  
This reference may help:  
[random() / Reference / Processing.org](https://processing.org/reference/random_.html)  
You will have to convert the _float_ to an _int_ to access elements of array:  
[int() / Reference / Processing.org](https://processing.org/reference/intconvert_.html)
3. Search for _timer_ (or related keywords) in this forum for examples of timers.
4. Write some code to understand each element above.
5. Start piecing the elements of code together and later integrate it into your project.

`:)`

---

<div class="post-metadata">

**Author:** ![micuat](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micuat/32/19407_2.png) [@micuat](https://discourse.processing.org/u/micuat)\
**Post date:** [April 24, 2024, 11:46am UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/3 "2024-04-24T11:46:08Z")

</div>

hi, welcome to the community!

I think this tutorial helps:

> **[Flappy Bird](https://thecodingtrain.com/challenges/31-flappy-bird/)**
>
> It's time to attempt to build a Flappy Bird clone in JavaScript with the p5.js!

If you have specific questions, it would be great if you can post your code (even if it’s super simple).

---

<div class="post-metadata">

**Author:** ![dsdsdsds](https://avatars.discourse-cdn.com/v4/letter/d/9f8e36/32.png) [@dsdsdsds](https://discourse.processing.org/u/dsdsdsds)\
**Post date:** [April 25, 2024, 7:35pm UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/4 "2024-04-25T19:35:12Z")

</div>

Thanks for the guidance, I’ve looked through the resources provided and others that I found online and wrote some code for what I’m trying to achieve.

I’m dealing with a problem:

When the first image or “enemy” spawns, it will work correctly for the length of spawnInterval, but after this period, instead of a new image spawning at x = 0, the current image on the sketch will teleport to a new randomised y co-ordinate, with the speed noticeably increasing once this happens.

As well as that, a new image spawns on top of the previous one and they move simultaneously.

My goal is to have it work so a new image will spawn at every 2.5 second interval, and that the images will disappear once they reach the width of the sketch, which in this case is 800px. I also want the speed to stay the same for every enemy.

I’m unsure how to achieve that at this point, any help would be appreciated.

Here is my starting code:

```auto
String[] imageNames = {"square1.png", "square2.png", "square3.png", "square4.png", "square5.png"};
PImage[] images = new PImage[imageNames.length];
PImage bg;
int playerX, playerY, currentTime;
int spawnInterval = 2500;
float y, startTime;
float x = 0;
float speed = 3;
boolean[] imageVisible = new boolean[images.length];

void setup()
{
  bg = loadImage("background.png");
  size(800, 600);
  playerX = width/2;
  playerY = height/2;
  noCursor();
  startTime = millis();

  for (int i = 0; i < images.length; i++) {
    images[i] = loadImage(imageNames[i]);
    imageVisible[i] = false;
  }
}

void draw()
{
  image(bg, 0, 0);
  timeLoop();
  imageMovement();
  playerX = mouseX;
  playerY = mouseY;
  fill(255, 0, 0);
  ellipse(playerX, playerY, 30, 30);
}

void imageMovement()
{
  for (int i = 0; i < images.length; i++)
  {
    if (imageVisible[i])
    {
      x+= speed;
      image(images[i], x, y);
      if (x >= width)
      {
        imageVisible[i] = false;
      }
    }
  }
}

void timeLoop()
{
  currentTime = millis();
  if (currentTime - startTime >= spawnInterval)
  {
    spawnImage();
    startTime = currentTime;
  }
}

void spawnImage()
{
  int randomIndex = int(random(images.length));
  y = random(height - images[randomIndex].height);
  image(images[randomIndex], x, y);
  imageVisible[randomIndex] = true;
}

```

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [April 25, 2024, 9:00pm UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/5 "2024-04-25T21:00:49Z")

</div>

> [@dsdsdsds](#):
>
> I’m unsure how to achieve that at this point, any help would be appreciated.

You may wish to consider an object oriented approach:

- [Objects / Processing.org](https://processing.org/tutorials/objects)
- [Using Objects - Happy Coding](https://happycoding.io/tutorials/processing/using-objects)
- [8.1: What is Object-Oriented Programming (OOP)? - Processing Tutorial](https://www.youtube.com/watch?v=YcbcfkLzgvs)

Example:

> **[Bouncy Bubbles / Examples](https://processing.org/examples/bouncybubbles.html)**
>
> Multiple-object collision.

It make take some time but the reward is well worth the effort.

`:)`

---

<div class="post-metadata">

**Author:** ![LangdonS](https://avatars.discourse-cdn.com/v4/letter/l/ebca7d/32.png) [@LangdonS](https://discourse.processing.org/u/LangdonS)\
**Post date:** [April 30, 2024, 2:30pm UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/6 "2024-04-30T14:30:12Z")

</div>

You can use:  
`ArrayList<PImage> images = new ArrayList<PImage>(); `

However, you really should create an Enemy class.

```auto
class Enemy{
float x,y;
Enemy(){
//Constructor
}
void show(){
//show image
}
}

```

Then, just create an `ArrayList` of Enemies.  
`ArrayList<Enemy> enemies = new ArrayList<Enemy>();`

You should have a `Player` class too.

---

<div class="post-metadata">

**Author:** ![LangdonS](https://avatars.discourse-cdn.com/v4/letter/l/ebca7d/32.png) [@LangdonS](https://discourse.processing.org/u/LangdonS)\
**Post date:** [April 30, 2024, 2:31pm UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/7 "2024-04-30T14:31:45Z")

</div>

Avoid calling `image(PImage img, float x, float y, float xSize, float ySize)`; it degrades performance.

Always call `image(PImage img, float x, float y)` instead.

If you need to resize your images, resize the file so the computer does not have to resize them EVERY time.

---

<div class="post-metadata">

**Author:** ![LangdonS](https://avatars.discourse-cdn.com/v4/letter/l/ebca7d/32.png) [@LangdonS](https://discourse.processing.org/u/LangdonS)\
**Post date:** [April 30, 2024, 2:34pm UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/8 "2024-04-30T14:34:44Z")

</div>

Why use `int(4.0f)` when `(int) 4.0f` is likely better?

The Processing method `dist(float x1, float y1, float x2, float y2)` is very inefficient (no clue why).  
Use this instead:

```auto
    double fastDist(double x1, double y1, double x2, double y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

```

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [April 30, 2024, 4:09pm UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/9 "2024-04-30T16:09:31Z")

</div>

We can also clone [via **get()**] the PImage and **resize()** it once in **setup()**, before **draw()** starts.

---

<div class="post-metadata">

**Author:** ![LangdonS](https://avatars.discourse-cdn.com/v4/letter/l/ebca7d/32.png) [@LangdonS](https://discourse.processing.org/u/LangdonS)\
**Post date:** [April 30, 2024, 8:48pm UTC](https://discourse.processing.org/t/using-array-of-images-to-spawn-enemies-in-game/44341/10 "2024-04-30T20:48:43Z")

</div>

Cool!

That is a good approach.  
I had no idea such a thing existed.
