I created my first Animation class which calls Animation_SS. To make this class I take code from: https://github.com/libgdx/libgdx/wiki/2D-Animation . I transformed code from this site to my class. I dont know why but after run program it's immediately closed. I use libGDX lib. Here is console output
Exception in thread "LWJGL Application" java.lang.NullPointerException
at AnimationDemo.AnimationDemo.render(AnimationDemo.java:78)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
It shows render method.
And here is main class
public class AnimationDemo extends ApplicationAdapter {
Animation_SS walkGuy;
SpriteBatch batch;
@Override
public void create () {
walkGuy = new Animation_SS(6, 0.025f, true);
walkGuy.loadSS("StickSS.png");
walkGuy.cropSS(4, 2);
}
@Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
walkGuy.loadCurrentFrame();
batch.begin();
walkGuy.drawFrame(batch,10,10);
batch.end();
}
}
And here is Animation_SS class
int cols;
int rows;
int totalFrames;
float duration;
float stateTime=0f;
Boolean restart;
Texture texture;
TextureRegion[] frames;
TextureRegion currentFrame;
Animation myAnimation;
SpriteBatch batch;
public Animation_SS(int totalFrames, float duration, Boolean letItRestart){
this.totalFrames = totalFrames;
this.duration = duration;
this.restart = letItRestart;
}
public void loadSS(String path){
texture = new Texture(Gdx.files.internal(path));
}
public void cropSS(int FRAME_COLS, int FRAME_ROWS){
this.cols = FRAME_COLS;
this.rows = FRAME_ROWS;
TextureRegion[][]framesArray = TextureRegion.split(texture, texture.getWidth()/FRAME_COLS, texture.getHeight()/FRAME_ROWS);
frames = new TextureRegion[totalFrames];
int index = 0;
for (int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(index<totalFrames)
frames[index++] = framesArray[i][j];
}
}
myAnimation = new Animation(duration, frames);
}
public void loadCurrentFrame(){
stateTime +=1 *Gdx.graphics.getDeltaTime();
currentFrame = myAnimation.getKeyFrame(stateTime, restart);
}
public void drawFrame(SpriteBatch batch, float x, float y){
batch.draw(currentFrame,x ,y);
}
}
I guess you are forgetting to initialize the SpriteBatch
object, I don't see this line somewhere in your code:
batch = new SpriteBatch();
so when you call the batch.begin();
in the render()
method you will get a NPE
because this object was not created.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.