Ive just started with andEngine the past week and i only started learning java/android 3 weeks.

I can use a for loop to add multiple sprites to the screen but when i try to check collisions on them it only does it to one and not the rest.

I want to be able to add a specific number for sprites made from the same texture to the scene, add collision detection to them and also make them slide across the screen (im making a game where you avoid the obstacles).

2 Answers
2

The sample code you provided is not going to allow you to do collision detection or the like, because you're not holding references to multiple sprites--instead, you're replacing the same field. Let me give you an example that resembles your code, but simplifies the problem:

If I ran this I would have no way of comparing one of the values of x with another value of x, because the older x value is constantly getting rewritten with no reference.

This is somewhat analogous to your code. Your createObstacle(int) method repeatedly calls your createObstacle(float, float) method, and the latter repeatedly sets the same obstacle field. So you're not holding a reference to multiple obstacles, you're only holding one.

Arrays

One solution would simply be to use multiple fields. In my example above, instead of having just an x variable, I could have a y, a z, and so forth. A better approach would be to use an array, and an even better approach would be to use a java collection. First Arrays:

In my example code above, instead of using int x, I could declare an array of ints, like this:

int[] myArray = new int[10];

This declares an array of ints and allocates memory for 10 of them. Now I could set individual ints in the array by putting the reference number in brackets. Like this:

Note, arrays start counting at zero, not at one, and if you attempt to access or place data outside the bounds of what was allocated, you'll get an error. These and other reasons are why it often makes sense to use one of the java collections instead of an array.

ArrayList Example

There are a number of different java collections with different feaures and benefits for different situations. An ArrayList is a handy simple one that avoids the problem described above of having to know the total size in advance. You create an ArrayList like this:

Sidenote, I'm not a huge fan of the names of your methods. Having two methods called createObstacle() when only one of them creates an obstacle is going to lead to confusion.
–
Cameron FredmanFeb 18 '13 at 16:42