user7841697
user7841697

Reputation: 5

Texture not rotating with the object

I have a very simple object and a texture drown to it (using shader). Everything works great, except when rotating the object, the texture is not rotating along it, but appears to stay in the 2D space, creating the 'mask' effect below:

Texture not rotating along the object

When I use a regular material and attach texture to it, all works fine, so I'm guessing I'm doing something wrong at the vertex shader.

I load the model the following way:

var loader = new THREE.JSONLoader();

loader.load( "models/cube.json", addModelToScene );

var texture = THREE.ImageUtils.loadTexture( "images/woods.jpg" );
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 1.0, 1.0 );

uniforms = 
    {
        time: 
        { 
            type: "f", 
            value: 1.0 
        },
        texture1: { type: "t", value: THREE.ImageUtils.loadTexture( "images/woods.jpg" ) }

    };

function addModelToScene( geometry, materials ) {
      var material       = new THREE.MeshFaceMaterial( materials );
      var shaderMaterial = new THREE.ShaderMaterial
      (
          {
              vertexShader:   $('#vertexshader').text(),
              fragmentShader: $('#fragmentshader').text(),
              uniforms:       uniforms
          }
      );

     model = new THREE.Mesh( geometry, shaderMaterial );
     model.scale.set( 2.5, 2.5, 2.5 );
     scene.add( model );
}

Vertex shader:

varying vec2 vUv;

#ifdef GL_ES
    precision highp float;
#endif

uniform float time;
uniform sampler2D texture1;

void main()
{
    vUv = uv;
    gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}

Fragment shader:

varying vec2 vUv;

#ifdef GL_ES
  precision highp float;
#endif

uniform sampler2D texture1;
uniform float time;

void main()
{
    vec2  u_resolution  = vec2( 1700, 1000 );
    vec2  uv            = gl_FragCoord.xy / u_resolution.xy;
    gl_FragColor        = texture2D( texture1, uv );
}

And finally I rotate the object the following way:

model.rotation.z += 0.00013;
model.rotation.z += 0.004;

Why is the texture not one with the object, but instead stays in static position? Thanks!

Upvotes: 0

Views: 273

Answers (1)

Kirill Dmitrenko
Kirill Dmitrenko

Reputation: 3649

That's because you should use vUv varying to address the texture, not gl_FragCoord.xy:

gl_FragColor = texture2D(texture1, vUv);

gl_FragColor.xy is just pixel's (or, to be more accurate, fragment's) coordinates on a screen (i.e., window coordinates). They don't depend on rotation (or any transformations for that matter) of your object (or the object itself). They only depend upon where the pixel currently being shaded lies on the screen.

Upvotes: 2

Related Questions