根据错误信息,你的程序在尝试创建 World 对象时出现了 NullPointerException,这通常是因为传递给 World 构造函数的重力参数为 null。在 Box2D 中,一个 World 对象需要两个参数:重力向量和是否启用物理体休眠。
以下是你需要确认和调整的代码:
修改 World 创建代码
world = new World(new Vector2(0, -9.8f), true);
这里,我们需要提供一个 Vector2 对象来表示重力。通常,设置重力为 (0, -9.8f) 可以模拟地球上的重力。
完整示例代码
以下是经过调整后的完整代码:
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.Box2D;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import box2dLight.PointLight;
import box2dLight.RayHandler;
public class Box2DLightsDemo extends ApplicationAdapter {
private World world;
private Box2DDebugRenderer debugRenderer;
private OrthographicCamera camera;
private RayHandler rayHandler;
private Body groundBody;
@Override
public void create() {
Box2D.init();
world = new World(new Vector2(0, -9.8f), true);
debugRenderer = new Box2DDebugRenderer();
camera = new OrthographicCamera(Gdx.graphics.getWidth() / 32f, Gdx.graphics.getHeight() / 32f);
// Create ground body
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(0, -10);
groundBody = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox(50, 10);
groundBody.createFixture(groundBox, 0.0f);
groundBox.dispose();
// Initialize RayHandler
RayHandler.useDiffuseLight(true);
rayHandler = new RayHandler(world);
rayHandler.setCombinedMatrix(camera);
rayHandler.setAmbientLight(0.5f);
// Create a point light
PointLight light = new PointLight(rayHandler, 128);
light.setPosition(5, 5);
light.setDistance(10);
}
@Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
debugRenderer.render(world, camera.combined);
rayHandler.updateAndRender();
}
@Override
public void dispose() {
world.dispose();
debugRenderer.dispose();
rayHandler.dispose();
}
}
Gradle 配置
确保在你的 build.gradle 文件中正确配置了依赖项。对于 LibGDX 和 Box2DLights,你需要在 dependencies 部分加入这些依赖:
dependencies {
implementation "com.badlogicgames.gdx:gdx:$gdxVersion"
implementation "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
implementation "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
implementation "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
implementation "com.badlogicgames.gdx:gdx-backend-lwjgl3:$gdxVersion"
// 添加 box2dLight 库
implementation "com.badlogicgames.box2dlights:box2dlights:1.5"
}
请确保 gdxVersion 是你项目使用的 LibGDX 版本。
运行项目
重新构建并运行项目,如果 build.gradle 文件中没有其他错误,应该可以正常启动并显示包含光源和地面的简单场景。
如果遇到其他错误,请检查错误日志,并根据问题进行具体分析和调整。