Loop inside class instancing problem

Hi guys!

I’m currently developping a 3D game with processing for a University project. The game is actually a fighter jet poursuit. I have a radar in 2D who map the distance between the enemies and my jet. I have an ArrayList for my enemies and another one for the little circles in the radar (representation of the enemy).

The problem is that each circle get the same X and Y from one enemy.

Here’s my code:

``````public class EnemyRadar {

float x;
float y;
float sizeE;

EnemyRadar(float posX, float posY, float currentSizeE) {
//constructor
x = posX;
y = posY;
sizeE = currentSizeE;
}

void update() {
for (int i = 0; i < enemy.size(); i++) {
Enemy enemy_temp = enemy.get(i);
enemyRadarX = map(enemy_temp.x, 300, 1500, 150, 450);
enemyRadarY = map(enemy_temp.z, -100, 500, 600, 850);
this.x = enemyRadarX;
this.y = enemyRadarY;
}
}

void display() {
pushMatrix();
pushStyle();
noFill();
translate(x, y);
stroke(255, 0, 0);
ellipse(0, 0, sizeE, sizeE);
popStyle();
popMatrix();
}
}

``````
1 Like

I can see the problem. Generally it is better to show more code, or a runnable version, to understand your full approach. I am interested to know how you are instantiating`EnemyRadar()` in your application. Anyways, what you are doing within the update function:

`````` void update() {
for (int i = 0; i < enemy.size(); i++) {
....

}
``````

This is not proper. Every enemy should have their own x and y position in the radar. There are two approaches that would solve the problem. One is not good and the other is better:

Not good but it will work: Change x and y into an array. Something like this:

``````public class EnemyRadar {
float x[];
float y[];
...

``````

Then you need to init the arrays in the `EnemyRadar` constructor, for instance. This approach is not good because it defeats the core concept of using classes in OOP: encapsualtion. This is not a good practice and it works here because you have access to the global scope. I shows this so you can understand the second solution.

Better approach:
A better approach is to generate an array of `EnemyRadar` objects. When you call update, instead of accessing the enemy array from the global scope of your application, you should just pass to it each enemy as a parameter to your function:

``````void update(Enemy enemy_temp) {
enemyRadarX = map(enemy_temp.x, 300, 1500, 150, 450);
enemyRadarY = map(enemy_temp.z, -100, 500, 600, 850);
x = enemyRadarX;
y = enemyRadarY;
}
``````

Notice the first case (the not-good) will work and it will take less effort to implement. However it will make your code harder to maintain. The second approach is one way to do things like this with room for further improvement.

Kf

2 Likes