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