package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.ScreenUtils;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
AnimatedSprite sprite;
@Override
public void create () {
batch = new SpriteBatch();
img = new Texture("mario-spritesheet.png");
sprite = new AnimatedSprite(img, 4, 4, 0, 0);
}
@Override
public void render () {
ScreenUtils.clear(0, 0, 0, 1);
sprite.stay();
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
sprite.move(2);
} else {
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)){
sprite.move(-2);
} else {
if (Gdx.input.isKeyPressed(Input.Keys.DOWN)){
sprite.sit();
}
}
}
if (Gdx.input.isKeyPressed(Input.Keys.UP)){
sprite.jump();
}
batch.begin();
sprite.draw(batch);
batch.end();
}
@Override
public void dispose () {
batch.dispose();
img.dispose();
}
}
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class AnimatedSprite {
public static float FRAME_DURATION = 0.1f;
private TextureRegion [][] frames;
private int currentFrameX = 0, currentFrameY = 0;
private float currentFrameDuration = 0;
private int posX = 0, posY = 0;
private int orientation = 0;
public AnimatedSprite (Texture texture, int countX, int countY, int posX, int posY){
int width = texture.getWidth() / countX;
int height = texture.getHeight() / countY;
frames = new TextureRegion[countY * 2][countX];
TextureRegion [][] regions = TextureRegion.split(texture, width, height);
for(int i = 0; i < regions.length; i++){
for(int j = 0; j < regions[i].length; j++){
frames[i][j] = regions[i][j];
frames[i + countY][j] = new TextureRegion(regions[i][j]);
frames[i + countY][j].flip(true, false);
}
}
this.posX = posX;
this.posY = posY;
}
public void sit(){
if (orientation >= 0){
currentFrameY = 3;
} else {
currentFrameY = 7;
}
}
public void jump(){
if (orientation >= 0){
currentFrameY = 2;
} else {
currentFrameY = 6;
}
}
public void move(int dx){
orientation = dx;
if (dx > 0){
currentFrameY = 1;
} else {
currentFrameY = 5;
}
posX += dx;
}
public void stay(){
if (orientation >= 0){
currentFrameY = 0;
} else {
currentFrameY = 4;
}
}
public void draw(SpriteBatch batch){
currentFrameDuration += Gdx.graphics.getDeltaTime();
if (currentFrameDuration >= FRAME_DURATION){
currentFrameX = (currentFrameX + 1) % frames[currentFrameY].length;
currentFrameDuration -= FRAME_DURATION;
}
batch.draw(frames[currentFrameY][currentFrameX], posX, posY);
}
}