2017-02-10 84 views
0

我有一個簡單的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

,如果任何人有更多的經驗可以看到我的錯誤超級感激

回答

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

如果你想畫的圖像只是由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; 
}