Touch code only working at center of screen in my ball game using libgdx

自古美人都是妖i 提交于 2019-12-02 06:04:38

问题


My score does not increment after I touch the ball. It increments only when I touch the ball and its near the center of my screen. When my ball only moves in x axis keeping y constant the touch works fine. But when both are incremented the score increases only when touched at the center.

@Override
public void render () {


    batch.begin();

    Gdx.gl.glClearColor(1,1,1,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.draw(ball,xposi,yposi,100,100);

    if(gameState==1) {


        if (Gdx.input.justTouched()) {

            tmp = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
            textureBounds = new Rectangle(xposi, yposi, 100, 100);

            if (textureBounds.contains(tmp.x, tmp.y)) {
                Gdx.app.log("Click", "On Ball");
                score++;
                } 
           else {
                Gdx.app.log("Click", "Not on Ball");
                }
            }



        font.draw(batch, String.valueOf(score), 100, 300);
        font.draw(batch, String.valueOf(lives), 200, 300);

        xposi+=velocity;
        yposi+=velocity;

        if (xposi >= xmax - 100) {

            velocity = -velocity;
        } else if (xposi <= xmin) {

            velocity = -velocity;
        }

        if (yposi >= ymax - 100) {

            velocity = -velocity;
        } else if (yposi <= ymin) {

            velocity = -velocity;
        }

        batch.end();
     }
 }

回答1:


In libgdx, when we draw something on screen then the screen origin is bottom left corner but when we detect touch then screen origin is top left corner.

When you deal with horizontal movement then there is no involvement of y coordinate so it's work fine. You detect touch on ball when your ball is in center then the value of Gdx.input.getY() is approximately same to Gdx.graphics.getHeight()-Gdx.input.getY() so sometimes works.

so simple solution is just invert touch coordinate origin to bottom left corner.

tmp = new Vector3(Gdx.input.getX(),Gdx.graphics.getHeight()-Gdx.input.getY(), 0);

Recommendation :

Don't create object in render method like you're creating object of Rectangle and Vector3, create object in show() or create() method and set value to these variable in render() method.



来源:https://stackoverflow.com/questions/42231393/touch-code-only-working-at-center-of-screen-in-my-ball-game-using-libgdx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!