因此,我目前正在为玩家重构我的游戏代码,并启动了一个玩家类:
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Player
{
protected String name;
protected float health, maxHealth;
protected Texture texture;
protected int xPos, yPos;
public Player(String name, float maxHealth, Texture texture) {
this(name, maxHealth, texture, 0, 0);
}
public Player(String name, float maxHealth, Texture texture, int xPos, int yPos) {
this.name = name;
this.health = this.maxHealth = maxHealth;
this.texture = texture;
this.xPos = xPos;
this.yPos = yPos;
}
public Texture getTexture() {
return this.texture;
}
public int getX() {
return xPos;
}
public int getY() {
return yPos;
}
public String getName() {
return name;
}
public void draw(SpriteBatch spriteBatch) {
spriteBatch.begin();
spriteBatch.draw(texture, xPos, yPos, 0.5f, 0.5f, 0, 0,
texture.getWidth(), texture.getHeight(), false, false);
spriteBatch.end();
}
public void update(float delta) {
processMovement(delta);
}
public void processMovement(float delta) {
if(Gdx.input.isKeyPressed(Input.Keys.A)) {
xPos -= 50 * delta;
}
if(Gdx.input.isKeyPressed(Input.Keys.D)) {
xPos += 50 * delta;
}
}
}
我使用的是正交相机,我还没有添加任何地形,因为我接下来会这样做,但是我希望玩家始终留在中心但是有玩家我画画时会在地形上移动。
我创建相机和绘制播放器的代码如下:
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class GameState implements Screen
{
private PixelGame parent;
private OrthographicCamera camera;
private Player player;
private Texture playerTexture;
private SpriteBatch spriteBatch;
public GameState(PixelGame parent) {
this.parent = parent;
this.playerTexture = new Texture(Gdx.files.internal("player/sprite.png"));
this.player = new Player("Me", 20, playerTexture);
this.spriteBatch = new SpriteBatch();
}
@Override
public void render(float delta) {
camera.update();
spriteBatch.setProjectionMatrix(camera.combined);
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
player.draw(spriteBatch);
player.update(delta);
}
@Override
public void show() {
}
@Override
public void dispose() {
}
@Override
public void resize(int width, int height) {
float ratio = (float)width / (float)height;
camera = new OrthographicCamera(2f * ratio, 2f);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
}
玩家精灵似乎没有移动,但是当我将值更改为> 75时,玩家精灵在屏幕上冲刺,就像没有人一样。
答案 0 :(得分:2)
xPos
和yPos
是整理的。我会说这就是问题所在。您的processMovement()
方法被调用为每秒100次,50 * delta
很可能小于1,因此它舍入为0,因为值必须存储在int变量中。尝试将xPos
和yPos
更改为浮点数。
如果这没有帮助(不能在不尝试代码的情况下确定)做一些调试。放点破发点。查看是否完全调用processMovement()
,如果是,则变量delta具有什么值。如何计算。