我正在使用libGDX,Tiled Map和Box2D製作平臺。我想申請一些着色器。libGDX着色器座標和相機位置
我想要一個貼着英雄的小插曲效果。對於小插曲效果,我使用了this tutorial。 我遇到的問題是:如果照相機是固定的,我就會得到我想要的。小插曲貼在英雄身上。但是,如果攝像機移動,在滾動的一些平臺遊戲中發生,則小插曲效果不會粘在英雄身上。
Here is a video that illustrates my problem
看來我得考慮到攝像機的位置來計算的暈影效果的座標,但是我不知道怎麼樣。 這裏是片段着色器我用了小插曲:
varying vec4 v_color;
varying vec2 v_texCoord0;
uniform vec2 u_resolution;
uniform float u_PosX, u_PosY;
uniform sampler2D u_sampler2D;
const float outerRadius = 10, innerRadius = 1, intensity = .5;
void main(){
vec4 color = texture2D(u_sampler2D, v_texCoord0) * v_color;
vec2 relativePosition = gl_FragCoord.xy/u_resolution - vec2(u_PosX, u_PosY); //Position of the vignette
relativePosition.x *= u_resolution.x/u_resolution.y; //The vignette is a circle
float len = length(relativePosition);
float vignette = smoothstep(outerRadius, innerRadius, len);
color.rgb = mix(color.rgb, color.rgb * vignette, intensity);
gl_FragColor = color;
}
在遊戲畫面中,相關代碼:
public TestScreen(final MyGdxGame gam){
camera = new MyCamera();
camera.setToOrtho(false, width, height);
camera.update();
vertexShader = Gdx.files.internal("Shaders/vVignette.glsl").readString();
fragmentShader = Gdx.files.internal("Shaders/fVignette.glsl").readString();
shaderProgram = new ShaderProgram(vertexShader,fragmentShader);
shaderProgram.begin();
shaderProgram.setUniformf("u_resolution", camera.viewportWidth, camera.viewportHeight);
shaderProgram.end();
}
public void render(float delta) {
Gdx.gl.glClearColor(0.1f,0.1f,0.1f,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
//calculation of the position of the effect depending on the position of the hero
posX = (Gdx.graphics.getWidth()/camera.viewportWidth) * hero.bodyHero.getPosition().x/camera.viewportWidth;
posY = (Gdx.graphics.getHeight()/camera.viewportHeight) * hero.bodyHero.getPosition().y/camera.viewportHeight;
shaderProgram.begin();
shaderProgram.setUniformf("u_PosX", posX);
shaderProgram.setUniformf("u_PosY", posY);
shaderProgram.end();
}
正如我所說的,這個代碼工作完美,如果相機沒有移動。但由於相機抖動時,我想這個問題是有聯繫的攝像機投影和我嘗試這個代碼,沒有更好的成功,在渲染() 它不工作:
Vector3 PosHero = new Vector3();
PosHero.set(hero.bodyHero.getPosition().x, hero.bodyHero.getPosition().y, 0);
camera.unproject(PosHero);
posX = (Gdx.graphics.getWidth()/camera.viewportWidth) * PosHero.x/camera.viewportWidth;
posY = (Gdx.graphics.getHeight()/camera.viewportHeight) * PosHero.y/camera.viewportHeight;
shaderProgram.begin();
shaderProgram.setUniformf("u_PosX", posX);
shaderProgram.setUniformf("u_PosY", posY);
shaderProgram.end();
您沒有提供足夠的信息,看看http://stackoverflow.com/help/how -to-ask,尤其是http://stackoverflow.com/help/mcve。 – Xoppa