Getting sprite position on world inside shader

Getting sprite position on world inside shader
0.0 0

#1

Hi,
any way i can get sprite position on world without passing it using Uniform ,i wanna use one shader on multiple sprites and i want to get each sprite position in world ,I have moving camera and the shader is not moving with the camera .

 float distance = sqrt(pow(gl_FragCoord.x - lightPosition[i].x, 2.0) + pow(gl_FragCoord.y - lightPosition[i].y, > 2.0));

using gl_FragCoord will not move with the camera .lightPosition is the position of the light, any way i can do that ?


#2

the default shader of sprite is noMVP, so the value “a_position” in the vert file is the value of sprite’s world position, you can simply pass the value to .frag file,
for example:

attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
varying vec2 v_position;

void main()
{
gl_Position = CC_PMatrix * a_position;
v_fragmentColor = a_color;
v_texCoord = a_texCoord;
v_position = a_position.xy;
}


#3

i’ve tested that and it worked on shapes ,but on sprites the position did’t work .


#4

in my case I write my own light class, and all the lights and sprites are under the default camera. I move the parent layer to simulate camera moving. In my shader of sprite I pass the light’s world position and use the a_position of sprite to calculate the light effect.


#5

i’m doing the same ,but the sprites are inside other layer and the layer inside the parent layer .im not sure if thats the issue.


#6

So gl_fragCoord will give you the position in screen space

Which means you have to convert vertices into screen space


#7

ive test that ,it only work if the position is gl_Position = CC_MVPMatrix * a_position; and it did’t work on gl_Position = CC_PMatrix * a_position;