Search code examples
javalibgdxbox2dlightbox2dlights

Java / box2DLights - Wrong light position


I'm using Libgdx for a project and more precisely Box2DLights.

My problem is the following one : When I want to put a new "PointLight" it's always on the center of the screen. And if I change the coordinates, it doesn't work.

Inside my "show()" method :

    Box2D.init();
    world = new World(new Vector2(0, 0), true);

    rh = new RayHandler(world);
    rh.setAmbientLight(1.2f, 0.2f, 0.2f, 0.1f);
    pl = new PointLight(rh, 100, new Color(1,1,1,1),(float) 0.5,0,0);

Inside my "render()" method :

    Gdx.gl.glClearColor(0f, 0f, 0f, 1f); 
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    world.step(delta, 8, 3);

    renderer.begin(ShapeType.Filled);
    for (SolarSystem ss : solarSystemList)
    {
        if(ss.getColor() <= 15) colorSS = Color.YELLOW;
        else if(ss.getColor() > 15 && ss.getColor() < 31) colorSS = Color.ORANGE;
        else if(ss.getColor() > 30 && ss.getColor() < 46) colorSS = Color.RED;
        else if(ss.getColor() > 45) colorSS = Color.CYAN;

        renderer.setColor(colorSS);
        renderer.circle(ss.getMapX(), ss.getMapY(), ss.getSize() - 3);
    }
    renderer.end();

    rh.updateAndRender();

Result :

enter image description here Now if I try to change coordinates :

pl = new PointLight(rh, 100, new Color(1,1,1,1),(float) 0.5, 50, 50);

enter image description here

... no light anymore

Do you know how it's possible to put the light where I want ?

EDIT : My screen size : width - 860px / height - 645px


Solution

  • if the (1,1) is the top right and the (0,0) is bottom left and the (0.5,0.5) is the middle of the screen, then i propose to do this : insert the value that you want and divide it by the width and height of of your screen for example

     ( xPosition/Gdx.graphics.width, yPosition/Gdx.graphics.height ) 
    

    Update :

    sorry i didn't see that (0,0) was the center so i propse to you to use this instead :

    width  = Gdx.graphics.width;
    height = Gdx.graphics.height;
    ((xPosition - width/2)/ width/2 , (yPosition - height/2)/ height/2)
    

    Update 2 : i think you are doing little arithmetic mistake assume that your

    width = 860 and your height = 645 as you said

    this is the equation :

    x= ((xPosition - width/2)/ width/2)

    y= (yPosition - height/2)/ height/2)

    x = (50 - 860/2) / (860/2)

    y = (50 - 645/2) / (645/2)

    x = (50 - 430) / (430)

    y = (50 - 322.5) / (322.5)

    x = (50 - 430) / (430) = (-380) / (430)

    y = (50 - 322.5) / (322.5) = (-272.5) / (322.5)

    x = -0.88

    y = -0.84

    which is closer to (-1,-1) aka : the left bottom corner

    hope it was helpful :)