So, I have been playing around with vertex and fragment shaders, and wanted to know if there was a way to add shadows to the fragment shaders? I have tried many unsuccessful attempts, and researched a bunch, but nothing seems to work. I’ve seen the method to turn the shader material into something different, but I am hesitant to do that as it seems sketchy.
const vertexShader = `
varying vec2 vUv;
uniform float time;
const int numOfObjects = 8;
uniform vec3 positions[numOfObjects];
uniform vec3 ballPosition;
uniform bool anim;
void main() {
vUv = uv;
vec4 grassPosition = instanceMatrix * vec4(position, 1.0);
if(anim){
vec4 prevGrassPos = grassPosition;
float bendFactor = grassPosition.y * grassPosition.y * 2.0;
for(int i = 0; i<numOfObjects; i++){
vec3 toObject = grassPosition.xyz - positions[i];
float distanceToObject = length(toObject);
if(distanceToObject < 1.1){
if(positions[i].x > grassPosition.x){
grassPosition.x -= bendFactor;
} else if(positions[i].x < grassPosition.x){
grassPosition.x += bendFactor;
}
if(positions[i].z > grassPosition.z){
grassPosition.z -= bendFactor;
} else if(positions[i].z < grassPosition.z){
grassPosition.z += bendFactor;
}
}
}
if (prevGrassPos == grassPosition && grassPosition.y > 0.1){
grassPosition.x += sin(grassPosition.y*grassPosition.y + time*7.0)/7.0;
}
}
gl_Position = projectionMatrix * modelViewMatrix * grassPosition;
}
`;
const fragmentShader = `
varying vec2 vUv;
void main() {
vec3 baseColor = vec3( 0.41, 1.0, 0.5 );
float clarity = vUv.y * vUv.y * 0.4 + 0.35;
gl_FragColor = vec4( baseColor * clarity, 1);
}
`;
I would like the grass to receive a shadow from the wall next to it.
If you would like to see the game for yourself: https://ethantwu.com/minigames/3dgame.html
And the source code is here[Grass code starts on line 86]: https://github.com/LeftClickMage/ethantwu.com/blob/main/minigames/test3d.js