Arrays LibGdx对象数组
我在libGdx项目中创建了一个对象数组,如下所示:Arrays LibGdx对象数组,arrays,object,libgdx,Arrays,Object,Libgdx,我在libGdx项目中创建了一个对象数组,如下所示: Array<Bird> birds = new Array<Bird>(); 这里我只需要10个对象。但当我尝试打印数组大小时,它会不断增加。我如何正确地实现这一点? 我还想知道如何使用spriteBatch绘制这些数组对象。 如果我能从代码中得到解释,那将非常有帮助。您必须在每次for循环运行时创建一个新的Bird对象。因此,编写birds.add(objectFactory.createBird())而不是bir
Array<Bird> birds = new Array<Bird>();
这里我只需要10个对象。但当我尝试打印数组大小时,它会不断增加。我如何正确地实现这一点?
我还想知道如何使用spriteBatch绘制这些数组对象。
如果我能从代码中得到解释,那将非常有帮助。您必须在每次for循环运行时创建一个新的
Bird
对象。因此,编写birds.add(objectFactory.createBird())
而不是birds.add(b)
。我认为这应该可以纠正第一个错误
您需要以某种方式实现如下所述:
但我真的建议您使用,因为它非常易于使用,并且您可以找到大量的教程。您必须为每个for循环运行创建一个新的
Bird
对象。因此,编写birds.add(objectFactory.createBird())
而不是birds.add(b)
。我认为这应该可以纠正第一个错误
您需要以某种方式实现如下所述:
但我真的建议您使用,因为它非常易于使用,并且您可以找到大量的教程。为了保持
birds
数组的大小不变,您需要将MakeBird()函数修改为该函数
private void MakeBird() {
int birdsToAdd = 10 - birds.length;
for (int i = 0; i < birdsToAdd ; i++) {
birds.add(objectFactory.createBird());
}
}
为了保持birds
数组的大小不变,您需要将MakeBird()
函数修改为
private void MakeBird() {
int birdsToAdd = 10 - birds.length;
for (int i = 0; i < birdsToAdd ; i++) {
birds.add(objectFactory.createBird());
}
}
您的MakeBird()
方法创建一个bird并将其添加到数组中十次,这可能不是您想要的。对于不断增加的大小,您是否对每一帧调用MakeBird()
,而不是一次?您的MakeBird()
方法创建一个bird并将其添加到数组中十次,这可能不是您想要的。对于不断增加的大小,您是否在每一帧上调用MakeBird()
,而不是一次?
public class Game implements ApplicationAdapter {
private SpriteBatch batch;
private Texture texture;
public void create () {
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("example.png"));
}
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // This cryptic line clears the screen.
batch.begin();
batch.draw(texture, 10, 10);
batch.end();
}
}
private void MakeBird() {
int birdsToAdd = 10 - birds.length;
for (int i = 0; i < birdsToAdd ; i++) {
birds.add(objectFactory.createBird());
}
}
//Bird class
class Bird {
//Your data members
//Your member functions
public void draw(SpriteBatch batch) {
batch.draw(some_bird_image, bird_x_position, bird_y_position);
}
}
//Render method in main class
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
for(Bird bird : birds) {
bird.draw(batch);
}
batch.end();
}