Скорость объекта в libgdx

Я изучаю разработку libgdx, и у меня возникают проблемы при редактировании демо:

Я редактирую официальную демонстрацию Flappy Bird, я удалил камни и добавил несколько пуль (справа налево), вот мой код:

public class FGame implements Screen {

// General constants
private static final float PLANE_JUMP_IMPULSE = 350;
private static final float GRAVITY = -20;
private static final float PLANE_VELOCITY_X = 200;
private static final float PLANE_START_Y = 240;
private static final float PLANE_START_X = 50;
private static final float BULLET_SPEED_X = 5;
// Timer constants
private static final float TIME_BULLET_REPEAT = 2;
private static final float TIME_FUEL_REPEAT = 5;
private static final float TIME_FUEL_DECREASE = 5;

// Render && Batch
ShapeRenderer shapeRenderer;
SpriteBatch batch;

// Camera
OrthographicCamera camera;
OrthographicCamera uiCamera;

// Texture from Background && Ceiling
Texture background;
TextureRegion ground;
float groundOffsetX = 0;
TextureRegion ceiling;

// Plane animation && position && speed && gravity
Animation plane;
Vector2 planePosition = new Vector2();
Vector2 planeVelocity = new Vector2();
float planeStateTime = 0;
Vector2 gravity = new Vector2();

// Ready && Game Over signs
TextureRegion ready;
TextureRegion gameOver;

// Font used for Fuel% && Score
BitmapFont font;

// Bullet texture && Sprite && ArrayList && timer from bullets
Texture bulletTexture;
Sprite bulletSprite;
ArrayList<Bullet> bulletList;
float bulletTime;

// Fuel texture && Sprite && ArrayList && Timer
Texture fuelTexture;
Sprite fuelSprite;
ArrayList<Fuel> fuelList;
float fuelTime;

// GameState && Rectangles
GameState gameState = GameState.Start;
int score = 0;
Rectangle rect1 = new Rectangle();

// Music and effects
Music music;
Sound explode;

private void resetWorld() { // Used in the first time and in GameOver
    score = 0;
    groundOffsetX = 0;
    planePosition.set(PLANE_START_X, PLANE_START_Y);
    planeVelocity.set(0, 0);
    gravity.set(0, GRAVITY);
    camera.position.x = 400;
    if (!bulletList.isEmpty())
        bulletList.removeAll(bulletList); // Remove objects every new Game
    if (!fuelList.isEmpty())
        fuelList.removeAll(fuelList);
}

private void updateWorld() { // Used every frame update
    float deltaTime = Gdx.graphics.getDeltaTime();
    planeStateTime += deltaTime;
    bulletTime += deltaTime;
    fuelTime += deltaTime;

    if (Gdx.input.justTouched()) {
        if (gameState == GameState.Start) {
            gameState = GameState.Running;
        }
        if (gameState == GameState.Running) {
            planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
        }
        if (gameState == GameState.GameOver) {
            gameState = GameState.Start;
            resetWorld();
        }
    }

    if (gameState != GameState.Start) {
        planeVelocity.add(gravity);
        // Timer functions
        if (bulletTime >= TIME_BULLET_REPEAT) { // Create bullets over time.
            bulletTime -= TIME_BULLET_REPEAT;
            createBullet();
        }
        if (fuelTime >= TIME_FUEL_REPEAT) { // Create fuel over time
            fuelTime -= TIME_FUEL_REPEAT;
            createFuel();
        }
        if (!bulletList.isEmpty()) { // bullets movement.
            for (Bullet bullet : bulletList) {
                bullet.bulletSprite.setX(bullet.bulletSprite.getX()
                        - BULLET_SPEED_X);
            }
        }
    }

    planePosition.mulAdd(planeVelocity, deltaTime);

    camera.position.x = planePosition.x + 350;
    if (camera.position.x - groundOffsetX > ground.getRegionWidth() + 400) {
        groundOffsetX += ground.getRegionWidth();
    }

    rect1.set(planePosition.x + 20, planePosition.y,
            plane.getKeyFrames()[0].getRegionWidth() - 20,
            plane.getKeyFrames()[0].getRegionHeight());

    if (planePosition.y < ground.getRegionHeight() - 20
            || planePosition.y + plane.getKeyFrames()[0].getRegionHeight() > 480 - ground
                    .getRegionHeight() + 20) {
        if (gameState != GameState.GameOver)
            explode.play();
        gameState = GameState.GameOver;
        planeVelocity.x = 0;
    }
}

private void createBullet() {
    bulletList.add(new Bullet(Gdx.graphics.getWidth(), bulletSprite));

    for (Bullet bullet : bulletList) {
        if (!bullet.isSet()) {
            bullet.bulletSprite.setBounds(planePosition.x + 1000,
                    bullet.getY(), 100, 100);
            bullet.Set();
            score++;
        }
    }
}

private void createFuel() {
    fuelList.add(new Fuel(Gdx.graphics.getWidth(), fuelSprite));

    for (Fuel fuel : fuelList) {
        if (!fuel.isSet()) {
            fuel.fuelSprite.setBounds(planePosition.x + 1000,
                    fuel.getY(), 50, 50);
            fuel.Set();
            score++;
        }
    }
}

private void drawWorld() {
    camera.update();
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(background, camera.position.x - background.getWidth() / 2, 0);

    batch.draw(ground, groundOffsetX, 0);
    batch.draw(ground, groundOffsetX + ground.getRegionWidth(), 0);
    batch.draw(ceiling, groundOffsetX, 480 - ceiling.getRegionHeight());
    batch.draw(ceiling, groundOffsetX + ceiling.getRegionWidth(),
            480 - ceiling.getRegionHeight());
    batch.draw(plane.getKeyFrame(planeStateTime), planePosition.x,
            planePosition.y);
    if (!bulletList.isEmpty()) { // Draw Bullets
        for (Bullet bullet : bulletList) {
            bullet.bulletSprite.draw(batch);
        }
    } // End Draw Bullets
    if (!bulletList.isEmpty()) { // Draw Fuel
        for (Fuel fuel : fuelList) {
            fuel.fuelSprite.draw(batch);
        }
    } // End Draw Fuel
    batch.end();

    batch.setProjectionMatrix(uiCamera.combined);
    batch.begin();
    if (gameState == GameState.Start) {
        batch.draw(ready,
                Gdx.graphics.getWidth() / 2 - ready.getRegionWidth() / 2,
                Gdx.graphics.getHeight() / 2 - ready.getRegionHeight() / 2);
    }
    if (gameState == GameState.GameOver) {
        batch.draw(
                gameOver,
                Gdx.graphics.getWidth() / 2 - gameOver.getRegionWidth() / 2,
                Gdx.graphics.getHeight() / 2 - gameOver.getRegionHeight()
                        / 2);
    }
    if (gameState == GameState.GameOver || gameState == GameState.Running) {
        font.draw(batch, "" + score, Gdx.graphics.getWidth() / 2,
                Gdx.graphics.getHeight() - 60);
    }
    batch.end();
}

static enum GameState { // Enum for gameStates
    Start, Running, GameOver
}

@Override
public void show() { // Method called instead of create()

    // Loading shapeRenderer && batch
    shapeRenderer = new ShapeRenderer();
    batch = new SpriteBatch();

    // Loading camera
    camera = new OrthographicCamera();
    camera.setToOrtho(false, 800, 480);
    uiCamera = new OrthographicCamera();
    uiCamera.setToOrtho(false, Gdx.graphics.getWidth(),
            Gdx.graphics.getHeight());
    uiCamera.update();

    // Loading Font
    font = new BitmapFont(Gdx.files.internal("arial.fnt"));

    // Loading Background && Ceiling
    background = new Texture("background.png");
    ground = new TextureRegion(new Texture("ground.png"));
    ceiling = new TextureRegion(ground);
    ceiling.flip(true, true);

    // Plane frames && animation
    Texture frame1 = new Texture("plane1.png");
    frame1.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    Texture frame2 = new Texture("plane2.png");
    Texture frame3 = new Texture("plane3.png");
    plane = new Animation(0.05f, new TextureRegion(frame1),
            new TextureRegion(frame2), new TextureRegion(frame3),
            new TextureRegion(frame2));
    plane.setPlayMode(PlayMode.LOOP);

    // Bullet Textures && List
    bulletTexture = new Texture("img/bullet.png");
    bulletSprite = new Sprite(bulletTexture);
    bulletList = new ArrayList<Bullet>();

    // Fuel Textures && List
    fuelTexture = new Texture("img/fuel.png");
    fuelSprite = new Sprite(fuelTexture);
    fuelList = new ArrayList<Fuel>();

    // Loading Ready && gameOver Signs
    ready = new TextureRegion(new Texture("ready.png"));
    gameOver = new TextureRegion(new Texture("gameover.png"));

    // Music load && play
    music = Gdx.audio.newMusic(Gdx.files.internal("music.mp3"));
    music.setLooping(true);
    music.play();

    // Effect load
    explode = Gdx.audio.newSound(Gdx.files.internal("explode.wav"));

    // Call resetWorld for the first time.
    resetWorld();

}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    updateWorld();
    drawWorld();
}

Пули нарисованы правильно, но по какой-то причине скорость x увеличивается каждый раз, когда создается пуля.

Здесь я редактирую движение пуль по оси x:

if (!bulletList.isEmpty()) { // bullets movement.
            for (Bullet bullet : bulletList) {
                bullet.bulletSprite.setX(bullet.bulletSprite.getX()
                        - BULLET_SPEED_X);
            }

Это мой класс пули

public class Bullet {
private float y;
private float x;
private boolean bulletSet = false;
public Sprite bulletSprite;

public Bullet(float x, Sprite bulletSprite) {
    this.x = x;
    this.bulletSprite = bulletSprite;

    y = MathUtils.random(50, 450);
}

public boolean isSet() {
    return bulletSet;
}

public void Set() {
    bulletSet = true;
}

public float getY () {
    return y;
}

public float getX () {
    return x;
}

Вы можете найти проблему?


person Edw4rd    schedule 13.05.2015    source источник
comment
В настоящее время вы можете отображать только одну пулю, верно? Мне кажется, что у вас есть только один экземпляр спрайта, общий для всех объектов пули. Таким образом, скорость спрайта действительно в настоящее время равна number_of_bullet*BULLET_SPEED_X.   -  person Khopa    schedule 13.05.2015


Ответы (1)


Проблема здесь, в вашем конструкторе Bullet:

this.bulletSprite = bulletSprite;

Все экземпляры пули ссылаются на один и тот же спрайт, поэтому вы меняете один и тот же спрайт снова и снова. Вместо этого вы должны сделать его копию при назначении спрайта новой пуле. Измените его на

this.bulletSprite = new Sprite(bulletSprite);

Кстати, похоже, что все ваши обращения к if (!bulletList.isEmpty()) лишние и их можно удалить. (просто чтобы упростить ваш код)

person Tenfour04    schedule 13.05.2015
comment
Это сработало отлично, большое спасибо. Теперь я правильно понимаю спрайты. - person Edw4rd; 13.05.2015