我刚开始使用
java和libgdx,并且有这个代码,很简单,它会在屏幕上打印一个sprite.这样做完美,我从中学到了很多东西.
package com.MarioGame; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.InputProcessor; public class Game implements ApplicationListener { private SpriteBatch batch; private Texture marioTexture; private Sprite mario; private int marioX; private int marioY; @Override public void create() { batch = new SpriteBatch(); FileHandle marioFileHandle = Gdx.files.internal("mario.png"); marioTexture = new Texture(marioFileHandle); mario = new Sprite(marioTexture,158,32,64); marioX = 0; marioY = 0; } @Override public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(mario,marioX,marioY); batch.end(); } @Override public void resume() { } @Override public void resize(int width,int height) { } @Override public void pause() { } @Override public void dispose() { }
}
解决方法
对于您手头的任务,您甚至可能不需要实现InputProcessor.你可以在这样的render()方法中使用Input.isKeyPressed()方法.
float marioSpeed = 10.0f; // 10 pixels per second. float marioX; float marioY; public void render() { if(Gdx.input.isKeyPressed(Keys.DPAD_LEFT)) marioX -= Gdx.graphics.getDeltaTime() * marioSpeed; if(Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)) marioX += Gdx.graphics.getDeltaTime() * marioSpeed; if(Gdx.input.isKeyPressed(Keys.DPAD_UP)) marioY += Gdx.graphics.getDeltaTime() * marioSpeed; if(Gdx.input.isKeyPressed(Keys.DPAD_DOWN)) marioY -= Gdx.graphics.getDeltaTime() * marioSpeed; Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(mario,(int)marioX,(int)marioY); batch.end(); }
还要注意,我做了马里奥浮标的位置坐标,并将运动改为时间运动.马里奥速度是马里奥每秒向任何方向行进的像素数. Gdx.graphics.getDeltaTime()返回自上次调用render()以来的传递时间(以秒为单位).在大多数情况下,转换为int实际上并不是必需的.
Btw,我们在http://www.badlogicgames.com/forum的论坛,你也问libgdx的具体问题!
心连心,马里奥