Java – how to use libgdx to move sprites using keyboard keys?

I've just started using Java and libgdx, and I have this code. It's very simple. It will print a sprite on the screen It's perfect. I've learned 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,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 to modify the mariox value when the user presses the D key on the keyboard?

Solution

For the task at hand, you may not even need to implement inputprocessor You can use input in such a render () method Iskeypressed() method

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 the Mario buoy and changed the motion to time motion Mario speed is the number of pixels Mario travels in any direction per second Gdx. graphics. Getdeltatime() returns the delivery time (in seconds) since render() was last called In most cases, conversion to int is not actually necessary

BTW, we're here http://www.badlogicgames.com/forum Forum, you also ask specific questions about libgdx!

Heart to heart, Mario

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>