代码之家  ›  专栏  ›  技术社区  ›  mugimugi

libgdx-检查身体是否接触

  •  1
  • mugimugi  · 技术社区  · 9 年前

    屏幕上有一些尸体( Ball[] balls ),并且我希望在用户触摸它们时删除它们。

    还有,我有一个 Image 作为身体的userData。

    我不想对所有人都起作用 形象 ,因为必须按顺序删除球。

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

    2 回复  |  直到 9 年前
        1
  •  3
  •   user5180607 user5180607    9 年前

    至少有两种方法我知道你可以用来完成这一点。

    方法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;
        }
    };
    

    因此,总而言之,您使用world对象的函数QueryAABB来检查某个位置上的固定装置。然后我们重写回调以从QueryCallback中的reportFixture函数获取主体。

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

    方法2:

    如果您正在使用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.
            }
        });
    }
    
        2
  •  0
  •   WorkerBeeCode    6 年前

    我觉得这是一个很好的解决方案:

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