在Libgdx 3d中的RayCasting [英] RayCasting in Libgdx 3d
问题描述
好吧所以我一直在尝试相当一段时间在libgdx中使用Raycast进行3D碰撞检测,基于我在哪里看..但是我画了一个空白,似乎没有任何文档。有人会非常友好地向我发送正确的方向吗?
Alright so I've been trying for quite some time too Raycast in libgdx for 3d collision detection based on where im looking.. But I've drawn a blank and doesn't seem to be any documentation anywhere. Would someone be kind enough to send me in the right direction?
推荐答案
使用libgdx来实现你的目标真的很容易试图做。以下是我用于进行射线测试并找到我的射线所能击中的最近碰撞对象的内容。我们假设它位于一个名为 BulletUtil
的类中。
It is actually really easy with libgdx to achieve what you are trying to do. The following is what I'm using to do a ray test and find the closest collision object that my ray would hit. Let's assume it is located in a class called BulletUtil
.
private static final Vector3 rayFrom = new Vector3();
private static final Vector3 rayTo = new Vector3();
private static final ClosestRayResultCallback callback = new ClosestRayResultCallback(rayFrom, rayTo);
public static btCollisionObject rayTest(btCollisionWorld collisionWorld, Ray ray) {
rayFrom.set(ray.origin);
// 50 meters max from the origin
rayTo.set(ray.direction).scl(50f).add(rayFrom);
// we reuse the ClosestRayResultCallback, thus we need to reset its
// values
callback.setCollisionObject(null);
callback.setClosestHitFraction(1f);
callback.getRayFromWorld().setValue(rayFrom.x, rayFrom.y, rayFrom.z);
callback.getRayToWorld().setValue(rayTo.x, rayTo.y, rayTo.z);
collisionWorld.rayTest(rayFrom, rayTo, callback);
if (callback.hasHit()) {
return callback.getCollisionObject();
}
return null;
}
现在你还需要一个 InputProcessor
对点击事件作出反应。
Now what else you need is an InputProcessor
that reacts on the click events.
public class BulletInputProcessor extends InputAdapter {
private Viewport pickingViewport;
private btCollisionWorld collisionWorld;
// a constructor which takes a Viewport and the collision world and stores them
public BulletInputProcessor(...) { ... }
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if (button == Input.Buttons.LEFT) {
Ray pickRay = pickingViewport.getPickRay(screenX, screenY);
btCollisionObject body = BulletUtil.rayTest(collisionWorld, pickRay);
if (body != null) {
// do whatever you want with this body now
return true;
}
}
return false;
}
}
视口
负责创建选择 Ray
。您应该在此处使用视口来管理用于渲染世界的 PerspectiveCamera
。不要忘记通过 Gdx.input.setInputProcessor(新的BulletInputProcessor(collisionWorld,viewport))
注册输入处理器。
The Viewport
is responsible to create the picking Ray
. You should use the viewport here which manages the PerspectiveCamera
that you use to render the world. Don't forget to register the input processor via Gdx.input.setInputProcessor(new BulletInputProcessor(collisionWorld, viewport))
.
这篇关于在Libgdx 3d中的RayCasting的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!