问题描述
我有一个简单的box2d世界,上面有一个平台和跟踪玩家的相机。 我试图在触摸屏幕的一侧时获得触摸输入控制,但是感觉比我想象的要复杂。 触摸屏幕有时会移动盒子,但是当我击中期望的位置时永远不会移动盒子,尝试通过在触摸的地方绘制图片进行调试只会导致更多的混乱。 这是相机或触摸聆听的所有代码
创建方法
public void create () {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
Gdx.input.setInputProcessor(new MyInputProcessor());
camera = new OrthographicCamera();
camera.setToOrtho(false, w/2, h/2);
touchpos = new Vector3();
world = new World(new Vector2(0, -9.8f), false);
b2dr = new Box2DDebugRenderer();
player = createBox(8, 10, 32, 32, false);
platform = createBox(0, 0, 64, 32, true);
}
渲染方法
public void render () {
update(Gdx.graphics.getDeltaTime());
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
b2dr.render(world, camera.combined.scl(PPM));
}
调整大小
public void resize(int width, int height) {
camera.setToOrtho(false, width / 2, height / 2);
}
相机更新
public void cameraUpdate(float delta){
Vector3 position = camera.position;
position.x = player.getPosition().x * PPM;
position.y = player.getPosition().y * PPM;
camera.position.set(position);
camera.update();
}
触摸输入法和数学
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
touchpos.set(screenX, screenY, 0);
camera.unproject(touchpos);
if (touchpos.x > 500){
touchleft = true;
}
else touchleft = false;
if (touchpos.x < 300){
touchright = true;
}
else touchright = false;
if (300 < touchpos.x && touchpos.x < 500){
touchcenter = true;
}
else touchcenter = false;
return true;
}
我认为它应该像使用原始触摸值一样简单而又不会弄乱相机,因为我希望用于控制的区域始终保持相同,但是那是行不通的,所以我上了google并尝试进行投影和其他摆弄使用相机,但触摸从未起作用。
我觉得答案应该很简单。 我需要的是,当它检测到屏幕左侧或右侧的触摸时,可以将相应的变量设置为true
如果有更多经验的人可以看到错误,我将不胜感激
1楼
scl()转换Matrix4(camera.combined)的值,因此不要缩放camera.combined。
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(30, 30 * (h / w));
public void render () {
update(Gdx.graphics.getDeltaTime());
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
b2dr.render(world, camera.combined);
}
您将要从事物理学工作,因此将移动物体的大小保持在约0.1米至10米之间,而不是大于10米。
如果要绘制图像,只需将box2d尺寸缩放30倍,并获得以像素为单位的尺寸。
对于触摸,您要根据设备的宽度和高度设置视口,并在预定义值上应用条件。
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
touchpos.set(screenX, screenY, 0);
camera.unproject(touchpos);
if (touchpos.x > camera.viewportWidth*.8f){
touchleft = true;
}
else touchleft = false;
if (touchpos.x < camera.viewportWidth*.2f){
touchright = true;
}
else touchright = false;
if (camera.viewportWidth*.2f< touchpos.x && touchpos.x < camera.viewportWidth*.8f){
touchcenter = true;
}
else touchcenter = false;
return true;
}