I'm new in libgdx and I have problems to add into my Array a rectangle ("two"). I can't detect collision after adding it and getting it. My code is bellow:
...
public class MyGdxGame implements ApplicationListener
{
Texture texture;
SpriteBatch batch;
Rectangle one, two;
float x1=0,x2;
float y1, y2;
Array <Rectangle> array;
In the Create():
texture = new Texture(Gdx.files.internal("android.jpg"));
batch = new SpriteBatch();
x2 = Gdx.graphics.getWidth()-40;
y1 = y2 = (Gdx.graphics.getHeight()/2)-15;
one = new Rectangle();
two = new Rectangle();
one.set(x1, y1, 40, 30);
two.set(x2, y2, 40, 30);
array = new Array <Rectangle>();
array.add(two);
In the Renderer():
...
batch.begin();
batch.draw(texture, x1, y1, 40, 30);
batch.draw(texture, x2, y2, 40, 30);
try
{
Thread.sleep(10);
x1 += 2;
x2 -= 2;
one.set(x1, y1, 40, 30);
two.set(x2, y2, 40, 30);
here is the problem, 'cause "one" rectangle doesn't detect the collision with the "two" rectangle:
if(one.overlaps(array.get(1)))
{
x1 = 0;
x2 = Gdx.graphics.getWidth()-40;
}
}
catch(Exception e){}
batch.end();
Can anybody help me please?
You are adding only 1 element into your array.
array.add(two);
To get to this object you should use: array.get(0);
instead of array.get(1);
Firstly I would suggest using List, and as you probably want to have multiple rectangles to check collision with them:
List<Rectangle> myList = new ArrayList<>();
myList.add(two);
for(Rectangle rect : myList) {
if(one.overlaps(rect)) {
//...
}
}