我刚开始使用libgdx,我是游戏开发的新手,我希望我的相机跟随我的精灵,但它不会跟随我的精灵(播放器),而是精灵只是来回移动很少不要向上(我想要)。
这是我的show()方法
public void show() {
world = new World(new Vector2(0, 25), true);
renderer = new Box2DDebugRenderer();
cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
cam.update();
Gdx.input.setInputProcessor(new InputController() {
@Override
public boolean keyDown(int keycode) {
if(keycode == Input.Keys.A)
box.setLinearVelocity(0f, 60f);
if(keycode == Input.Keys.D)
box.setLinearVelocity(0f, 20f);
if(keycode == Input.Keys.ESCAPE)
((Game) Gdx.app.getApplicationListener()).setScreen(new MainMenu());
return true;
}
@Override
public boolean keyUp(int keycode) {
if(keycode == Input.Keys.A)
box.setLinearVelocity(0f, 0f);
if(keycode == Input.Keys.D)
box.setLinearVelocity(0f, 0f);
return true;
}
});
shapeRenderer = new ShapeRenderer();
batch = new SpriteBatch();
texture = new Texture("img/imgs.png");
sprite = new Sprite(texture);
sprite.setSize(47, 45);
sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
sprite.setBounds(200, 200, 64, 64);
//sprite.setPosition(Gdx.graphics.getWidth()/2 -sprite.getWidth()/2, Gdx.graphics.getHeight()/2-sprite.getHeight()/2);
//Body definition
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(0, Gdx.graphics.getHeight()/2 - 250);
box = world.createBody(bodyDef);
//Polygon Shape
PolygonShape shape = new PolygonShape();
shape.setAsBox(10, 20);
//fixture definition
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 5f;
fixtureDef.friction = .5f;
box.createFixture(fixtureDef);
box.setUserData(sprite);
shape.dispose();
这是我的渲染方法
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.step(1/60f, 6, 2);
cam.position.set(0,sprite.getY()+sprite.getHeight()/2,0);
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.disableBlending();
batch.begin();
world.getBodies(tmpBodies);
for(Body body: tmpBodies)
if(body.getUserData() instanceof Sprite){
Sprite boxsprite = (Sprite) body.getUserData();
boxsprite.setPosition(body.getPosition().x - sprite.getHeight()/2, body.getPosition().y- sprite.getHeight()/2);
boxsprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
boxsprite.draw(batch);
}
batch.end();
shapeRenderer.setColor(Color.RED);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rect(0, 200, 50, 50);
shapeRenderer.translate(1, 0, 0);
shapeRenderer.end();
renderer.render(world, cam.combined);
}
这是我的调整大小方法
public void resize(int width, int height) {
cam.viewportWidth = width;
cam.viewportHeight = height;
cam.update();
}
我已经尝试了所有可能的解决方案,但无法获得所需的结果。 我只是希望我的相机跟随我的精灵,并且精灵也能正常工作。 请帮我提供更好的解决方案。提前谢谢