i have just started using java and libgdx and have this code, very simply it prints a sprite onto the screen. This works perfectly, and i learnt a lot from it.
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, 0, 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() {
}
}
How would I modify the marioX
value when a user presses D
on their keyboard?
For your task at hand you might not even need to implement InputProcessor. You can use the Input.isKeyPressed() method in your render() method like this.
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();
}
Also note that i made the position coordinates of mario floats and changed the movement to time-based movement. marioSpeed is the number of pixels mario should travel in any direction per second. Gdx.graphics.getDeltaTime() returns you the time passed since the last call to render() in seconds. The cast to int is actually not necessary in most situations.
Btw, we have forums at http://www.badlogicgames.com/forum where you ask libgdx specific questions as well!
hth, Mario