how to check collision between object from the same arrayList

hello,
i have this code to draw images and rectangles :


ArrayList enemies = enemy.getE();
		for (int i = 0; i < enemies.size(); i++) {
			Enemy tmpE = (Enemy) enemies.get(i);
			g2d.drawImage(tmpE.getI(), (int) tmpE.getX(), (int) tmpE.getY(),
					tmpE.getW(), tmpE.getH(), this);
			Rectangle tmpR = (Rectangle) tmpE.getBounds();
			g2d.draw(tmpR);
			enemyRects.add(tmpR);

		}

and this code to make them moves :


ArrayList enemies = enemy.getE();
		for (int i = 0; i < enemies.size(); i++) {
			Enemy tmpE = (Enemy) enemies.get(i);
			tmpE.moveForward(hero.getX(), hero.getY());
		}


i want to check if the Rectangles (inside enemyRects) intersects with each other, i tried this


for (int i = 0; i < enemyRects.size(); i++) {
			Rectangle tmpR = (Rectangle) enemyRects.get(i);
			if (tmpR.intersects(tmpR)) {
				System.out.println("Colliding");
			}
		}

but it always print “colliding” cause it’s checking the rectangle with it self,
i tried to do this


if (tmpR.intersects((Rectangle) enemyRects.get(i+1))) {
				System.out.println("Colliding");
			}

but i get an out of bounds error
so i want to ask if there is a code that can do this :


if(tmpR!=itSelf && tmpR.intersects(tmpR)){
				System.out.println("Colliding");
			}

thank you

I think this could be useful for you.

yes i tried that before, it lags soooo much !!
and it also keep printing “collide” even when they are not colliding

A really simple thing would be to do something like this:

public Enemey getFirstCollision(Enemy theEnemey, ArrayList<Enemey> enemies) {
    ArrayList<Enemey> enemeis = ...;

    for (int i=0; i<enemies.size(); i++) {
        Enemey e = enemies.get(i);
        if (e != theEnemey && theEnemey.intersects(e))
            return e;
    }
    return null;
}

The method returns the first other Enemy object that the given enemy collides with, or null if no collision exists.

Some things you should be doing:

  1. Use generics; you should rarely ever need to cast objects like you are doing. e.g.
//now the list only expects type Enemy... 
ArrayList<Enemy> list = new ArrayList<Enemey>();

//it will throw a compiler error if "e" is not of type Enemy
list.add(e);
  1. Add important methods like intersects() into your Enemy definition:
public class Entity {
     private Rectangle bounds = new Rectangle();
     private BufferedImage image;

     ....

     public boolean intersects(Entity e) {
         return e.bounds.intersects(this.bounds);
     }

     public void draw(Graphics g) {
         g.drawImage(this.image, (int)bounds.x, (int)bounds.y, (int)bounds.width, (int)bounds.height, null);
         g.draw(bounds);
     }
}

...

public class Enemy extends Entity {
   ... enemy specific stuff ...
}

Not only does this result in cleaner code when rendering and checking collisions (since you don’t need to touch the Rectangle object at all), but it also is more flexible for future changes. Let’s say you want one of your enemies to have a Circle bounds instead of Rectangle, you only need to change their draw() and intersects() methods.

  1. Use descriptive method names like getImage() instead of getI(). It’s important to code with some “good practice” as it will make your program easier to read/debug, and also less prone to errors.

@davedes
thanks a lot, that seems pretty good
the only problem now is that once again i had to re-do everything :-\

PS :
all i know to do with Java2D is drawing shapes,images and make them move with or without Key and/or Mouse listeners,
if i start learning lwjgl today, how much would it take me to reach that very low level i have now with Java2D ?
cause am starting to feel that am wasting my time here, i know that all my errors are not because of Java2D but sooner or later i had to stop developing with it and be forced to learn more advanced things,
what do you think ?
if i should start learning now, can you please post some “getting started” links ?

thank you

Basically, drawing Images:


public void drawImage(SpriteBatch batch, Sprite sprite) {
    sprite.draw(batch, xposition, yposition);
}

you can even have fun:


sprite.setRotation(100f); // rotated.
sprite.setScale(10, 10); // 10x scaled on both x and y axis

Loading sprites is pretty trivial too:


Texture tex = new Texture("myfile.png");
Sprite sprite = new Sprite(tex);

@matheus23

He is using Java 2D not LibGDX

davedes example is n^2. That’s fine if n is small. If it gets larger, you only need to check entities which are ahead of itself in the list as all behind have already checked themselves against the current one. Larger still: sweep and prune…larger still…spatial partitioning.

It was dedicated to this question:

When you stop quoting once… :confused: :slight_smile:

For the record this code is libgdx, not lwjgl (although libgdx uses lwjgl on desktop). Libgdx is a cross platform library and it is quite popular. I would consider it a less maths and graphics, more gamey library. lwjgl is more or less just a wrapping around the opengl functions with stuff like input and window creation thrown in.
In terms of lwjgl tutorials, check the wiki: http://www.lwjgl.org/wiki/index.php?title=Main_Page
There are tutorials on how to setup LWJGL, then read the basics section. Then learn about matrices (Nothing on the lwjgl wiki on them). Then read the 3.2 and newer stuff.
Or you can learn libgdx. I don’t use it so I can’t help you.

Argh… Forgot to add that…

I don’t think LWJGL is a good idea for a beginner. LWJGL is very low level; it doesn’t include anything like drawImage or drawRect. You have to build all of that yourself.

Instead, I would recommend LibGDX as suggested in many other threads. The good thing about LibGDX is that it tends to enforce better standards; i.e. using screens to make your game more modular, batching sprites, using texture atlases, etc.

Get started here:
http://libgdx.badlogicgames.com/documentation.html

It’s also good to look at how other games are written, as it will teach you a lot about “proper coding standards.”
https://github.com/libgdx/libgdx/tree/master/demos


[quote]the only problem now is that once again i had to re-do everything
[/quote]
This is how things tend to go when you are just beginning. You write something, and then realize there is a better way of doing it. :slight_smile: This is why your first couple games should be very simple; think Tic Tac Toe, Pong, etc.

[quote]if i start learning lwjgl today, how much would it take me to reach that very low level i have now with Java2D ?
[/quote]
With LWJGL, it might take a long time.

Here is an example in LibGDX that does all of this. If you study it you might be able to grasp it all within a day or two. It’s actually a complete little game:
http://www.java-gaming.org/?action=pastebin&id=557