如何将矩形添加到数组中?
How can I add a Rectangle into Array?
我是 libgdx 的新手,在向我的数组中添加一个矩形 ("two") 时遇到问题。添加并获取后我无法检测到碰撞。
我的代码如下:
...
public class MyGdxGame implements ApplicationListener
{
Texture texture;
SpriteBatch batch;
Rectangle one, two;
float x1=0,x2;
float y1, y2;
Array <Rectangle> array;
在 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);
在渲染器中():
...
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);
这是问题所在,因为 "one" 矩形没有检测到与 "two" 矩形的碰撞:
if(one.overlaps(array.get(1)))
{
x1 = 0;
x2 = Gdx.graphics.getWidth()-40;
}
}
catch(Exception e){}
batch.end();
有人可以帮我吗?
您只向数组中添加了 1 个元素。
array.add(two);
要获取此对象,您应该使用:array.get(0);
而不是 array.get(1);
首先,我建议使用 List,因为您可能希望有多个矩形来检查与它们的碰撞:
List<Rectangle> myList = new ArrayList<>();
myList.add(two);
for(Rectangle rect : myList) {
if(one.overlaps(rect)) {
//...
}
}
我是 libgdx 的新手,在向我的数组中添加一个矩形 ("two") 时遇到问题。添加并获取后我无法检测到碰撞。 我的代码如下:
...
public class MyGdxGame implements ApplicationListener
{
Texture texture;
SpriteBatch batch;
Rectangle one, two;
float x1=0,x2;
float y1, y2;
Array <Rectangle> array;
在 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);
在渲染器中():
...
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);
这是问题所在,因为 "one" 矩形没有检测到与 "two" 矩形的碰撞:
if(one.overlaps(array.get(1)))
{
x1 = 0;
x2 = Gdx.graphics.getWidth()-40;
}
}
catch(Exception e){}
batch.end();
有人可以帮我吗?
您只向数组中添加了 1 个元素。
array.add(two);
要获取此对象,您应该使用:array.get(0);
而不是 array.get(1);
首先,我建议使用 List,因为您可能希望有多个矩形来检查与它们的碰撞:
List<Rectangle> myList = new ArrayList<>();
myList.add(two);
for(Rectangle rect : myList) {
if(one.overlaps(rect)) {
//...
}
}