【问题标题】:libgdx - Check if body is touchlibgdx - 检查身体是否被触摸
【发布时间】:2015-08-01 17:24:53
【问题描述】:

我在屏幕周围有一些实体 (Ball[] balls),我想在用户触摸它们时删除它们。

另外,我有一个Image 作为身体的用户数据。

我不想对所有Image做一个函数,因为必须按顺序删除球。

检测身体是否被触摸的最佳方法是什么?

【问题讨论】:

    标签: java android libgdx touch box2d


    【解决方案1】:

    据我所知,您至少可以使用两种方法来完成此操作。

    方法一: 如果你使用的是 Box2D。

    在你的 touchDown 函数中,你可以有这样的东西:

        Vector3 point;
        Body bodyThatWasHit;
    
        @Override
        public boolean touchDown (int x, int y, int pointer, int newParam) {
    
            point.set(x, y, 0); // Translate to world coordinates.
    
            // Ask the world for bodies within the bounding box.
            bodyThatWasHit = null;
            world.QueryAABB(callback, point.x - someOffset, point.y - someOffset, point.x + someOffset, point.y + someOffset);
    
            if(bodyThatWasHit != null) {
                // Do something with the body
            }
    
            return false;
        }
    

    QueryAABB 函数中的 QueryCallback 可以这样重写:

    QueryCallback callback = new QueryCallback() {
        @Override
        public boolean reportFixture (Fixture fixture) {
            if (fixture.testPoint(point.x, point.y)) {
                bodyThatWasHit = fixture.getBody();
                return false;
            } else
                return true;
        }
    };
    

    因此,总而言之,您使用世界对象的函数 QueryAABB 来检查某个位置上的夹具。然后我们重写回调,从 QueryCallback 中的 reportFixture 函数中获取正文。

    如果您想查看此方法的实现,可以查看以下内容: https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTest.java

    方法二:

    如果您使用的是 Scene2D 或您的对象以某种方式扩展了 Actor 并且可以使用 clickListener。

    如果您使用 Scene2D 和 Actor 类,您可以将 clickListener 添加到您的 Ball 对象或图像。

    private void addClickListener() {
        this.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                wasTouched(); // Call a function in the Ball/Image object.
            }
        });
    }
    

    【讨论】:

    • 感谢您的回答。但它是如何用手指触摸的呢?我读到这门课是给callisions的,不是吗?
    • 感谢您的精彩解释,但是当我运行游戏并触摸一些身体时,有时它们会if(bodyThatWasHit != null) { // Do something with the body },有时则不会。另外,如果我触摸没有尸体的区域,它会进入 if 条件。
    【解决方案2】:

    我觉得这是一个不错的解决方案:

    boolean wasTouched = playerBody.getFixtureList().first().testPoint(worldTouchedPoint);
    if (wasTouched) {
        //Handle touch
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-20
      • 2016-07-28
      • 2012-02-14
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多