Java-Libgdx 3d中的RayCasting
作者:互联网
好的,所以我也已经尝试了相当长的时间,基于libgdx中的Raycast进行基于3D碰撞的3d碰撞检测.有人会友善地将我送往正确的方向吗?
解决方法:
libgdx实际上很容易实现您要尝试执行的操作.以下是我用来进行射线测试并找到射线将撞击的最接近碰撞对象的内容.假设它位于名为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.
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;
}
}
视口负责创建拾取光线.您应该在此处使用视口,该视口管理用于渲染世界的PerspectiveCamera.不要忘记通过Gdx.input.setInputProcessor(new BulletInputProcessor(collisionWorld,viewport))注册输入处理器.
标签:libgdx,collision-detection,raycasting,java 来源: https://codeday.me/bug/20191121/2051833.html