The object's texture remains static and does not follow its rotation

My simple object has a texture drawn onto it using a shader. Everything is working correctly, except when I rotate the object, the texture does not rotate along with it. Instead, it seems to remain in a 2D space, creating the 'mask' effect shown below:

Texture not rotating along the object

When I use a regular material and attach a texture to it, everything works as expected. Therefore, I suspect that the issue lies within the vertex shader.

This is how I load the model:

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 );
}

Finally, I rotate the object like this:

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

Why does the texture not rotate with the object, but instead remains in a static position? Any help is appreciated. Thank you!

Answer №1

To achieve the desired texture effect, it is recommended to utilize vUv for varying instead of gl_FragCoord.xy:

gl_FragColor = texture2D(texture1, vUv);

The values of gl_FragColor.xy represent the coordinates of the pixel or fragment on the screen. These coordinates remain unaffected by any transformations applied to the object, solely reflecting the position of the pixel being rendered on the screen.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The variable <something> has not been defined

Within my GitHub project, an error stating Uncaught ReferenceError: breakpoints is not defined is appearing in the Chrome console. This issue should be resolved by including breakpoints.min.js, but it seems that webpack is somehow causing interference. I ...

Tips for receiving dual return values from an AJAX request

I am sending an array of table IDs to retrieve the table numbers associated with those IDs from the database. I need to add up all the default seats for each table ID and return the total. JAVASCRIPT : function showUser(str) { if ...

Parenting and Child Components: Keeping the State in Sync

I am currently diving into my initial React project which focuses on a basic expense tracker for credit cards. While I'm still in the learning phase, I hope you can decipher the intent behind my code. My current roadblock involves mapping the state an ...

How can I dynamically adjust the stroke length of an SVG circle using code?

In my design project, I utilized Inkscape to create a circle. With the fill turned off, only the stroke was visible. The starting point was set at 45 degrees and the ending point at 315 degrees. After rotating it 90 degrees, here is the final outcome. < ...

User controls and the window.onload event handler

Is there a way for ASP.NET ASCX controls to have their own individual client-side load event, similar to a window.onload, allowing me to hide loading divs and display content divs once the HTTP transfer is finished? I'm struggling with implementing l ...

Issue finding a route based on dates

Hey everyone, I'm working on a feature where I need to fetch tasks made by a user within a specific date range provided by the user. However, I am facing some issues with getting the date and routing it. Here is the URL format that I am trying to work ...

Is it possible for the await block to be located outside of the async function that contains it?

setInterval(() => { // perform certain actions }, 1000) const bar = async () => { const response = await api_request(); do_actions(); } await bar(); When the foo function is set to run, will it interfere with the execution of the setInterval ...

Error: ReactJs unable to find location

I'm attempting to update the status of the current page when it loads... const navigation = \[ { name: "Dashboard", href: "/dashboard", current: false }, { name: "Team", href: "/dashboard/team", current: fa ...

The HTML anchor tag paired with the italic tag is a powerful combination for

Here is some example code: <a href="#"> <i class="some-bg" /> Some Text </a> Along with some Javascript: $("a").bind("touchstart", function (e) { e.preventDefault(); console.log("Tag: " + e.target); console.log("Tag Nam ...

Limit the width and height of MUI Popper with a maximum setting

After experimenting with the popper API from MUI, I discovered that it extends beyond my main div. Does anyone have suggestions on how to prevent this overflow? I am looking to increase the height of the popper. Please refer to the code snippet below: con ...

AngularJS dropdown menu for input selection binding

Hey there, I need some help with the code below: <input type="text" class="form-controlb" ng-model="item.name" id="name" placeholder="Enter Name" /> Also, I have a dropdown as shown here: <div class="col-sm-12" ng-model="query"& ...

The first time I try to load(), it only works partially

My script used to function properly, but it has suddenly stopped working. Can anyone help me figure out why? The expected behavior is for the referenced link to be inserted into target 1, while target 2 should be updated with new content from two addition ...

How can I uniquely combine a code with an existing CSS class and make modifications to it?

I am using ngx-skeleton-loader and I would like to change the color, but I am facing some difficulties. Here is an image that illustrates the issue. When looking at the developer tools, you can see the styles action in the styles action bar. .loader ...

Learning how to implement server side rendering in React JS through tutorials

After diving into the world of React js and mastering the basics, I successfully created web pages using this technology. I also honed my skills with node js and express. However, now I am faced with a new challenge: server side rendering. The tutorials av ...

Tips and tricks for selecting a specific element on a webpage using jQuery

How can I modify my AJAX form submission so that only the content within a span tag with the id "message" is alerted, instead of the entire response page? $.ajax({ url: '/accounts/login/', data: $(this).serialize(), success: function(ou ...

Failure to Fetch the Uploaded File's Value Using the Parameter

Objective: My aim is to automatically upload the second input named "file2" to the action result using jQuery code that is compatible with the latest versions of Firefox, Chrome, and Internet Explorer. Issue: The problem arises when HttpPostedFileBase ...

Integrate properties into a React component using an object as the representation

Can props be added to a component represented by an object? I am looking to add these props just once, within the map function, if possible. children: [ { id: '1', isActive: false, label: 'Home', component: & ...

Tips for verifying a list of objects within a request body with JOI

I'm in the process of validating the request body for an order placement. The request body contains an array of JSON objects that I need to validate, but I keep encountering the error message "productId" is required. Below is the structure of my requ ...

Exploring textboxes with jQuery loops

Is there a way to clear all these textboxes by iterating through them using Jquery? <div class="col-md-4" id="RegexInsert"> <h4>New Regex Pattern</h4> <form role="form"> <div class="form-group"> &l ...

minimize the size of the image within a popup window

I encountered an issue with the react-popup component I am using. When I add an image to the popup, it stretches to full width and length. How can I resize the image? export default () => ( <Popup trigger={<Button className="button" ...