我目前擁有我的主要人物「學生」的類,它除了左右移動之外沒有行爲。我設法做到了,所以我的Spritesheet的所有框架都會渲染,所以當我按下LEFT/RIGHT鍵時,我需要幫助繪製前3幀(這是漫步週期)。 這裏是spritesheet:http://imgur.com/a/HHdm9使用TextureRegion在Java中繪製部分精靈(LibGDX)
編輯:和第二和第三行按下向上和向下鍵時。
學生班級
public class Student {
private Texture player;
private Animation<TextureRegion> playerAnimation;
private int pX;
private int pY;
private SpriteBatch batch;
private int HP;
public Student(float speed, int x, int y){
player = new Texture("student.png");
TextureRegion[][] tmp= TextureRegion.split(player,450/3,450/3);
TextureRegion[] character = new TextureRegion[9];
int index = 0;
for(int i=0; i <3; i++){
for(int j=0; j < 3; j++){
character[index++] = tmp[i][j];}
}
playerAnimation = new Animation<TextureRegion>(speed,character);
pX=x;
pY=y;
}
public SpriteBatch getBatch() {
return batch;
}
public void setBatch(SpriteBatch batch) {
this.batch = batch;
}
public void goLeft(){
pX-=5;
if(pX < -10){
pX = -10;
}
}
public void goRight(){
pX+=5;
}
public void renderStudent(float stateTime){
TextureRegion currentFrame = playerAnimation.getKeyFrame(stateTime,true);
batch.draw(currentFrame, (float) pX, (float) pY, 0, 0, currentFrame.getRegionWidth(),
currentFrame.getRegionHeight(),1.5f,1.5f,0);
}
public void dispose(){
player.dispose();
}
}
主類
public class HaxMain extends ApplicationAdapter {
SpriteBatch batch;
Texture bg;
float stateTime;
private Student student1;
private Guard mguard, fguard;
private Admin madmin, fadmin;
@Override
public void create() {
batch = new SpriteBatch();
bg = new Texture("Level1.png");
student1 = new Student(.5f, 100, 0);
student1.setBatch(batch);
}
@Override
public void render() {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stateTime += Gdx.graphics.getDeltaTime();
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
student1.goLeft();
//Code to render image to the left
}else if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
//Code to render image to the right
student1.goRight();
}
batch.begin(); /*default code*/
batch.draw(bg, 0, 0);
student1.renderStudent(stateTime);
batch.end();
}
@Override
public void dispose() {
batch.dispose();
bg.dispose();
student1.dispose();
}
}
'student.png'文件裏面有多少幀,3幀是運行動作,其餘的都是? – Aryan
@AbhishekAryan他們都是3x3,最上面是行走的循環。第二排和第三排用於進入或退出房間,順便說一句,我的遊戲的sidescroller,角色可以進入一個房間,當敵人經過時隱藏。這裏有一個圖像http://imgur.com/a/HHdm9 –