LibGDX - SpotLight - How to implement Spot light in libgdx game ?


LibGDX - SpotLight
Spot lighting in libgdx is very easy Follow the instruction below. The only concern your have to draw a small white background image in your game screen just before light rendering.



public class MainGame extends ApplicationAdapter {
    SpriteBatch batch;
    Sprite img;
    private World world;
    private RayHandler rayHandler;
    private OrthographicCamera camera;
    private ExtendViewport viewport;
    private Texture texture;
    private PointLight pointLight;
    private Vector3 touchPoint = new Vector3();


    @Override
    public void create() {
        camera = new OrthographicCamera();
        viewport = new ExtendViewport(720, 1280, camera);

        batch = new SpriteBatch();
        img = new Sprite(new Texture("badlogic.jpg"));
        img.setPosition(100, 100);

        texture = new Texture("white.png");

        world = new World(new Vector2(0, 0), false);
        rayHandler = new RayHandler(world);
        rayHandler.setCulling(true);
        rayHandler.useDiffuseLight(true);
        rayHandler.setAmbientLight(1);

        pointLight = new PointLight(rayHandler, 1000, Color.WHITE, 1000, 500, 500);

    }

    @Override
    public void render() {
        camera.update();

        Gdx.gl.glClearColor(1f, 0f, 0f, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        batch.draw(texture, 0, 0, camera.viewportWidth, camera.viewportHeight);
        img.draw(batch); // Draw the circle of light
        batch.end();

        if (Gdx.input.isTouched()) {
            camera.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
            pointLight.setPosition(touchPoint.x, touchPoint.y);
        }

        rayHandler.setCombinedMatrix(camera);
        rayHandler.updateAndRender();


    }

    @Override
    public void resize(int width, int height) {
        viewport.update(width, height);
        camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
        camera.update();
    }


    @Override
    public void dispose() {
        batch.dispose();
        img.getTexture().dispose();
        texture.dispose();
        rayHandler.dispose();
    }
}



Comments