libgdx和box2d,屏幕触摸坐标无意义
问题描述:
我有一个简单的box2d世界,有一个平台和相机跟踪玩家。当我触摸屏幕的一侧时,我试图获得触摸输入控制,但感觉比我想象的更复杂。触摸屏幕偶尔会移动盒子,但从来没有当我点击我期望的位置,并尝试通过绘制图片进行调试时,我触摸的只会导致更多的混淆。这里的所有的相机或触摸听libgdx和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;
}
我想,我想用来控制是一样的始终区域但没它应该是为使用原始的触摸值,而无需用相机搞乱一样简单”工作,所以我采取谷歌和尝试unprojecting和做其他摆弄相机,但触摸从未工作。
我觉得答案应该很简单。我需要的是,当它检测到屏幕的左侧或右侧触摸它设置相应的变量设置为true
,如果任何人有更多的经验可以看到我的错误超级感激
答
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
如果你想画的图像只是由30扩展Box2D的尺寸之间以像素为单位获取尺寸
而对于触摸,您将根据设备宽度和高度设置视口,并将条件应用于预定义的值。
@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;
}