java - Drawing multiple sprites in libgdx -
i using libgdx 1.2.0 + eclipse. want draw multiple sprites class in game screen, 1 sprite gets drawn. render method
@override public void render(float delta) { gdx.gl.glclearcolor(100/255f, 0, 0, 1); gdx.gl.glclear(gl20.gl_color_buffer_bit); if(gdx.input.justtouched()){ touchx = gdx.input.getx(); touchy = gdx.input.gety(); //for(int i=0; < enemy.length; i++) //system.out.println(enemy[i].x + " " + enemy[i].y); } for(int i=0; i< enemy.length; i++){ enemy[i].update(delta); if(enemy[i].getsprite().getboundingrectangle().contains(touchx/ppx, touchy/ppy)) enemy[i].reset(); if(enemy[i].gameover){ gameover = true; //system.out.println("over"); } } game.batch.begin(); //if(!gameover){ for(int i=0; < enemy.length; i++) enemy[i].getsprite().draw(game.batch); //} game.batch.end(); }
same thing happens if call
enemy[0].getsprite().draw(game.batch); enemy[1].getsprite().draw(game.batch);
it draws if call 1 of them.
this enemy class. load same sprite game screen class in every instance of enemy, change it's position.
public class enemy { private final float minx=1, miny=2; private final float maxx=31, maxy=18; private float x,y; private float time; private sprite sprite; boolean gameover; public enemy(sprite sprite){ this.sprite = sprite; reset(); } public sprite getsprite(){ return sprite; } public void reset(){ x = minx + (int)(math.random() * (maxx - minx + 1)); y = miny + (int)(math.random() * (maxy - miny + 1)); time = 0.0f; gameover = false; sprite.setposition(x, y); } public void update(float delta){ time += delta; if(time >= 3.0f) gameover = true; } }
i load same sprite game screen class in every instance of enemy, change it's position.
it's problem, must create new sprite()
each enemy
object. however, when change sprite position of enemy, position of enemies changed.
as can see, reach same sprite doing enemy[0].getsprite()
or enemy[1].getsprite()
. can check reference equality enemy[0].getsprite()==enemy[1].getsprite()
.
you can solve issue like
public enemy(sprite sprite){ this.sprite = new sprite(sprite); reset(); }
another strange thing in code :
public void reset(){ x = minx + (int)(math.random() * (maxx - minx + 1)); y = miny + (int)(math.random() * (maxy - miny + 1)); time = 0.0f; gameover = false; sprite.setposition(x, y); }
if sprite.setposition(x, y)
, modifying x
, y
not enough change sprite's position. should improve update(float delta)
method in way, ensure sprite's position correctly updated.
public void update(float delta){ time += delta; if(time >= 3.0f) gameover = true; sprite.setposition(x, y); }
Comments
Post a Comment