[英]How to make a 'texture' jump up and return to starting position android java libgdx
所以我只是想让我的游戏角色,它是一个纹理( ball
),在空中跳跃,然后返回到按下屏幕时它开始的位置。 我只是想知道是否有人可以给我一个代码示例或帮助我使用下面的当前代码来做到这一点。 我基本上只是绘制了背景和球的纹理,并将球定位在我希望它开始跳跃的位置。 球的纹理是我想要直接跳起来的。
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture background;
Texture ball;
@Override
public void create () {
batch = new SpriteBatch();
background = new Texture("gamebackground.png");
ball = new Texture("ball2.png");
ball.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
}
@Override
public void render () {
batch.begin();
float scaleFactor = 2.0f;
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(ball, 80, 145, ball.getWidth() * scaleFactor, ball.getHeight() * scaleFactor);
batch.end();
}
@Override
public void dispose () {}
}
有一百万种方法可以做到这一点。
这是一个简单的(而且不是很灵活的方式)。 创建一个 Ball 类,其中包含 x 和 y 位置、速度和加速度的变量。 然后给它一个将加速度和速度应用到位置的更新方法:
public class Ball {
public static final float GRAVITY = -100; // size depends on your world scale
public static final float BOUNCE_DAMPENING = 0.6f;
public final Vector2 position = new Vector2();
public final Vector2 velocity = new Vector2();
public final Vector2 acceleration = new Vector2(0, GRAVITY);
public void update (){
float dt = Gdx.graphics.getDeltaTime();
velocity.add(acceleration.x * dt, acceleration.y * dt));
position.add(velocity.x * dt, velocity.y * dt);
if (position.y <= 0){ // hit ground, so bounce
position.y = -position.y * BOUNCE_DAMPENING;
velocity.y = -velocity.y * BOUNCE_DAMPENING;
}
}
}
这是处理物理学的一种非常基本的方法。 使用 Box2D 会更复杂,但如果您只是学习,上面的内容就可以了。
现在,您需要创建一个球实例并使用它来跟踪您的球位置。 绘制时使用 Ball 对象的位置。 您可以对点击做出反应以应用速度。
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture background;
Texture ballTexture;
Ball ball;
@Override
public void create () {
batch = new SpriteBatch();
background = new Texture("gamebackground.png");
ballTexture = new Texture("ball2.png");
ballTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
ball = new Ball();
}
@Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // don't forget to clear screen
if (Gdx.input.justTouched())
ball.velocity.y += 100;
ball.update();
batch.begin();
float scaleFactor = 2.0f;
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(ballTexture, ball.position.x, ball.position.y, ballTexture.getWidth() * scaleFactor, ballTexture.getHeight() * scaleFactor);
batch.end();
}
@Override
public void dispose () {
batch.dispose();
background.dispose();
ballTexture.dispose();
}
}
您还需要阅读像素单位与世界单位以及如何使用视口解决比例问题。 见https://xoppa.github.io/blog/pixels/和https://github.com/libgdx/libgdx/wiki/Viewports
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.