如何使精灵反弹屏幕的两侧

时间:2015-10-07 13:01:37

标签: java android libgdx

我在java android studio中使用libgdx。我刚刚开始。我正在开发Android手机。我没有使用任何相机。我想要的只是一个精灵弹跳屏幕的所有四边而不是点击。我尝试了许多代码,我认为它会起作用但不是。我希望你们能帮助我。我期待尽快回答。感谢

这就是我所拥有的:

QSerialPort portverf;
portverf.setBaudRate(QSerialPort::Baud9600);
portverf.setDataBits(QSerialPort::Data8);
portverf.setParity(QSerialPort::NoParity);
portverf.setStopBits(QSerialPort::OneStop);
portverf.setFlowControl(QSerialPort::NoFlowControl);
portverf.setPortName("COM41");
portverf.open();
port.write(command);
QString result = portverf.readAll();

}

1 个答案:

答案 0 :(得分:3)

我制作了你想要的一个非常简单的版本:

public class BouncyGame extends ApplicationAdapter {
    SpriteBatch batch;
    Texture ball;
    float speedX = 3f;
    float speedY = 3f;
    int x;
    int y;

    @Override
    public void create () {
        batch = new SpriteBatch();
        ball = new Texture("ball.png");
        x = Gdx.graphics.getWidth()/2;
        y = Gdx.graphics.getHeight()/2;
    }

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

        //When the ball's x position is on either side of the screen.
        //The width of the sprite is taken into account.
        if (x > Gdx.graphics.getWidth() - ball.getWidth()/2 || x < 0 + ball.getWidth()/2) {
            //Here we flip the speed, so it bonces the other way.
            speedX = -speedX;
        }
        //Same as above, but with on the y-axis.
        if (y > Gdx.graphics.getHeight() - ball.getHeight()/2 || y < 0 + ball.getHeight()/2) {
            speedY = -speedY;
        }

        //Move the ball according to the speed.
        x += speedX;
        y += speedY;

        batch.begin();
        //Draw the ball so the center is at x and y. Normally it would be drawn from the lower left corner.
        batch.draw(ball, x - ball.getWidth()/2, y - ball.getHeight()/2);
        batch.end();
    }
}

将产生以下结果:

http://gfycat.com/TatteredCarefreeHapuku

有很多方法可以改进这些代码,例如你可以使用向量,我不建议在你的最终产品中使用它,但它可能会帮助你弄清楚如何为你自己的项目做这样的事情。