0
我目前有一個動畫,只要我啓動應用程序就會運行。現在我想選擇另一個播放以響應用戶輸入的動畫。例如,如果我按左鍵,左邊的動畫會替換當前的精靈動畫。我試過在keyDown
函數中添加一個新的textureAtlas
,但這不起作用。響應輸入更改動畫
換句話說,我希望應用程序在沒有輸入時顯示精靈的空閒動畫。然後,如果我點擊一個按鈕(例如左側),它應該改變爲步行動畫。
package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
public class MyGdxGame extends ApplicationAdapter implements InputProcessor {
private SpriteBatch batch;
private TextureAtlas textureAtlas;
private Animation animation;
private float elapsedTime = 0;
@Override
public void create() {
batch = new SpriteBatch();
textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheet.atlas"));
animation = new Animation(1/7f, textureAtlas.getRegions());
}
@Override
public void dispose() {
batch.dispose();
textureAtlas.dispose();
}
@Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
//sprite.draw(batch);
elapsedTime += Gdx.graphics.getDeltaTime();
batch.draw(animation.getKeyFrame(elapsedTime, true), 0, 0);
batch.end();
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public boolean keyDown(int keycode) {
if (keycode == Input.Keys.LEFT) {
textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheet2.atlas"));
}
return true;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
}
請注意,TextureAtlases必須在丟失對它們的引用之前進行處理,否則會發生內存泄漏。當您調用'textureAtlas = new TextureAtlas ...'時,您將失去對實例化的第一個TextureAtlas的引用。 – Tenfour04
那麼,我會如何防止這種情況?我是否應該使用第三個TextureAtlas來保存第一個TextureAtlas,以便我可以處理它?或者有更好的方法來做到這一點? –
在將引用改爲別的之前調用它。通常,只有在切換階段時纔會這樣做。如果你的遊戲不是很大,你可能應該只有一個Atlas。在AssetManager上閱讀。 – Tenfour04