【问题标题】:Touch code only working at center of screen in my ball game using libgdx触摸代码仅在我的球赛中​​使用 libgdx 的屏幕中心工作
【发布时间】:2017-02-14 16:32:46
【问题描述】:

触球后我的分数没有增加。仅当我触摸球及其靠近屏幕中心时它才会增加。 当我的球只在 x 轴上移动并保持 y 不变时,触摸效果很好。但是当两者都增加时,只有在触摸中心时分数才会增加。

@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();
     }
 }

【问题讨论】:

    标签: android libgdx


    【解决方案1】:

    在 libgdx 中,当我们在屏幕上绘制东西时,屏幕原点是左下角,但当我们检测到触摸时,屏幕原点是左上角。

    当您处理水平移动时,不会涉及 y 坐标,因此可以正常工作。当您的球位于中心时,您会检测到触球,然后Gdx.input.getY() 的值与Gdx.graphics.getHeight()-Gdx.input.getY() 大致相同,因此有时会起作用。

    如此简单的解决方案就是将触摸坐标原点反转到左下角。

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

    建议:

    不要像创建 Rectangle 和 Vector3 的对象那样在 render 方法中创建对象,在 show()create() 方法中创建对象并在 render() 方法中为这些变量设置值。

    【讨论】:

    • 您可以按照docs 中的说明使用camera.unproject()
    • @LeonZ。我认为这个问题的所有者没有使用任何相机。
    • 关于你的建议,你的意思是我应该这样做:tmp​​.set(Gdx.input.getX(),Gdx.graphics.getHeight()-Gdx.input.getY(), 0); textureBounds.set(xposi,yposi,100,100);
    • @Shubhankar ya 在我看来这是更好的选择,创建一个新对象非常痛苦。
    • 嗨,Abhishek,我想在点击后增加球的速度我尝试在我的 afterTouch 代码中添加 if(velocity
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多