Question

this question is kinda embarassing, but i honestly can't find the bug. I have a Vertex Shader in my three.js environment. Since I will have many rotations on many objects in time, I figured I should use the shader to do it. But the rotation is not properly performed. The rotation is 2D and the y and z axis are flipped, fyi. Currently I'm rotating a cube . At PI/2(90 degrees), I just get a plane, where 2 points match each other.

Following the vertex shader. cos and sin are precalculated values of the same angle.

<script id="railbarVertexShader" type="x-shader/x-vertex">
    uniform float p1x;
    uniform float p1y;
    uniform float p1z;
    uniform float height;
    uniform float width;
    uniform float depth;
    uniform float sin;
    uniform float cos;

    varying vec2 vUv;
    varying vec3 vPosition;

    void main( void ) {
        vUv = uv;
        vPosition = position;

        //Scale
        vPosition.x *= width;
        vPosition.y *= height;
        vPosition.z *= depth;
        //Rotation + Position
        vPosition.y = vPosition.y+p1z;
        vPosition.x = (vPosition.x*cos)-(vPosition.z*sin)+p1x;
        vPosition.z = (vPosition.z*cos)+(vPosition.x*sin)+p1y;

        gl_Position = projectionMatrix * modelViewMatrix * vec4(vPosition, 1);

    }

</script>

The following image is the rotation at PI/4. You can already see how it is not a quadratic cube anymore. To PI/2, this worsens to a plane.

Rotated Cube

Im definetly missing something simple here, but I can't figure it out. Thanks in advance.

Was it helpful?

Solution

    vPosition.x = (vPosition.x*cos)-(vPosition.z*sin)+p1x;
    vPosition.z = (vPosition.z*cos)+(vPosition.x*sin)+p1y;

You are using the updated x-coordinate in the second line, but you should use the original x-coordinate (after scaling). I think that the code should look like:

void main(void)
{
    vUv = uv;

    // Scale
    float scaledX = position.x * width;
    float scaledY = position.y * height;
    float scaledZ = position.z * depth;

    // Rotation + Position
    vPosition.y = scaledY + p1z;
    vPosition.x = scaledX * cos - scaledZ * sin + p1x;
    vPosition.z = scaledZ * cos + scaledX * sin + p1y;

    gl_Position = projectionMatrix * modelViewMatrix * vec4(vPosition, 1);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top