缩放和定位都是动态的脚本中的不稳定行为 - 为什么?

Erratic behavior in script where both scale and positioning are dynamic - why?

我一直在努力隔离一个错误,当下面脚本中正方形的比例和位置都是动态的时,该错误会导致不稳定的行为。下面脚本的目标是让一个正方形在屏幕周围的不同位置和比例上淡入淡出。如果缩放和定位中的一个或两者是固定的,则行为符合预期 - 正方形以固定间隔和不同位置或不同比例(或固定位置和比例)上下淡入淡出。然而,如果缩放和位置都是动态的,那么这个正方形有时根本不会出现在屏幕上,最终几乎不会出现。怎么回事?

我在下面的代码片段中添加了动态部分和固定部分 scaling/positioning,这样您就可以自己尝试看看发生了什么。目前,我都设置为动态,因此您可以看到我描述的间歇性行为。感谢您的浏览并提出您的想法!

更新: 如果您喜欢那样工作,这里还有一个 fiddle

var container, renderer, scene, camera;
var gridComposer, finalComposer;
var container = document.body;

var frustrumWidth, frustrumHeight;
var frustrumSize = 1000;
var aspect; // = window.innerWidth / window.innerHeight;
var zoom = 0.5;
var imageWidth, imageHeight;

var width, height;

// Light Spot
var spot;



function init() {

    width = window.innerWidth;
    height = window.innerHeight;

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.setClearColor(0x000000);

    aspect = window.innerWidth / window.innerHeight;
    camera = new THREE.OrthographicCamera( frustrumSize * aspect / - 2, frustrumSize * aspect / 2, frustrumSize / 2, frustrumSize / - 2, 0, 2000 );
    camera.position.set( 0, 0, 100 );
    camera.zoom = zoom;
    camera.updateProjectionMatrix();

    frustrumWidth = (frustrumSize * aspect);
    frustrumHeight = frustrumSize;

    imageWidth = (frustrumWidth * 2);
    imageHeight = (frustrumHeight * 2);


    ///////////////////////////
    // Create the LIGHT spot //
    ///////////////////////////

    scene = new THREE.Scene();
    
    var opacity = 0.7;
    var material = new THREE.MeshBasicMaterial({ transparent: true, opacity: opacity, color: 0xffff00 });
    var spotSize;
    spotSize = 200;
    var geometry = new THREE.PlaneBufferGeometry(spotSize, spotSize);
    geometry.dynamic = true;
    var z = 1.01;
    var startPosition = chooseAWindowPosition( spotSize );
    startPosition.z = z;
    geometry.translate( startPosition.x, startPosition.y, startPosition.z );
    var fading = true;
    spot = [ new THREE.Mesh(geometry, material), fading, opacity, startPosition, spotSize ];
    scene.add(spot[0]);
    

    ////////////////////////
    // Create AxesHelpers //
    ////////////////////////

    // top left
    var axes1 = new THREE.AxesHelper( 100 );
    axes1.geometry.translate( -(imageWidth/2)+10, (imageHeight/2)-10, 0.01 );
    scene.add( axes1 );

    // top right
    var axes2 = new THREE.AxesHelper( 100 );
    axes2.geometry.translate( (imageWidth/2)-10, (imageHeight/2)-10, 0.01 );
    scene.add( axes2 );

    // bottom left
    var axes3 = new THREE.AxesHelper( 100 );
    axes3.geometry.translate( -(imageWidth/2)+10, -(imageHeight/2)+10, 0.01 );
    scene.add( axes3 );

    // bottom right
    var axes4 = new THREE.AxesHelper( 100 );
    axes4.geometry.translate( (imageWidth/2)-10, -(imageHeight/2)+10, 0.01 );
    scene.add( axes4 );

    // middle
    var axes5 = new THREE.AxesHelper( 100 );
    scene.add( axes5 );

    container.appendChild( renderer.domElement );
    render();
    
}

function randomIntFromInterval(min,max) { // min and max included
    return Math.floor(Math.random()*(max-min+1)+min);
}

function generateTranslationValues( beginPosition, endPosition ) { // generates the translate() values needed to move from one position to another
    var xDifference = endPosition.x - beginPosition.x;
    var yDifference = endPosition.y - beginPosition.y;
    var translateValues = new THREE.Vector3( xDifference, yDifference, 0 );
    console.log("beginPosition:");
    console.log(beginPosition);
    console.log("endPosition:");
    console.log(endPosition);
    console.log("translation values:");
    console.log(translateValues);
    return translateValues;
}

function generateScaleValue( origSpotSize, newSpotSize ) { // generates the scale values needed to rescale from one spot size to another
    scaleValue = newSpotSize / origSpotSize;
    console.log("Start size: " + origSpotSize);
    console.log("End size: " + newSpotSize);
    console.log("Scale value: " + scaleValue);
    return scaleValue;
}

function chooseAWindowPosition( spotSize ) {
    var position;
    var x;
    var y;
    x = randomIntFromInterval( -imageWidth / 2, imageWidth / 2 );
    y = randomIntFromInterval( -imageHeight / 2, imageHeight / 2 );
    position = new THREE.Vector3( x, y, 0 );
    console.log( "-imageWidth / 2 is" +  (-imageWidth / 2) );
    console.log( "imageWidth / 2 is" +  (imageWidth / 2) );
    console.log( "-imageHeight / 2 is" +  (-imageHeight / 2) );
    console.log( "imageHeight / 2 is" +  (imageHeight / 2) );
    console.log( "spotSize is: " + spotSize );
    console.log("position is:");
    console.log(position);
    return position;
}

function render() {
    renderer.render( scene, camera );
    requestAnimationFrame( render );
    updateLightSpot();
}

function updateLightSpot() {
    var fading = spot[1];
    if ( fading ) {
        spot[0].material.opacity-=0.007;
    } else { // if not fading
        spot[0].material.opacity+=0.007;
    }
    var opacityLimit = spot[2];
    var newFadeValue;
    if ( spot[0].material.opacity >= opacityLimit ) {
        spot[0].material.opacity = opacityLimit;
        newFadeValue = true;
        spot[1] = newFadeValue;
    } else if ( spot[0].material.opacity <= 0 ) {
        // >>> SCALING SECTION <<<
        var newSpotSize;
            // >>> FIXED SCALE <<<
        // newSpotSize = 200;
        // spot[4] = newSpotSize;
            // >>> DYNAMIC SCALE <<<
        newSpotSize = randomIntFromInterval( imageHeight*0.1, imageHeight*0.5 );
        var scaleValue;
        scaleValue = generateScaleValue( spot[4], newSpotSize );
        spot[0].geometry.scale( scaleValue, scaleValue, 1 ); // no change in scale for z
        spot[4] = newSpotSize;

        // >>> POSITIONING SECTION <<<
        var newPosition;
            // >>> FIXED POSITION <<<
        // newPosition = new THREE.Vector3( 0, 0, 0 );
        // var translateValues;
        // translateValues = generateTranslationValues( spot[3], newPosition );
        // spot[0].geometry.translate( translateValues.x, translateValues.y, translateValues.z );
        // spot[3] = newPosition;
            // >>> DYNAMIC POSITION <<<
        newPosition = chooseAWindowPosition( newSpotSize );
        var translateValues;
        translateValues = generateTranslationValues( spot[3], newPosition );
        spot[0].geometry.translate( translateValues.x, translateValues.y, translateValues.z );
        spot[3] = newPosition;

        newFadeValue = false;
        spot[1] = newFadeValue;
    }
}

init();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/95/three.js"></script>
<head>
  <title>three.js webgl - row of stripes with orthographic camera</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  <style>
   body {
    color: #ffffff;
    font-family:Monospace;
    font-size:13px;
    text-align:center;
    font-weight: bold;
    background-color: #000000;
    margin: 0px;
    overflow: hidden;
   }
   #info {
    color: #fff;
    position: absolute;
    top: 0px; width: 100%;
    padding: 5px;
    z-index:100;
   }
   a { color: #ff0000 }
  </style>
 </head>

 <body>

  <div id="info">Row Test</div>
  <!-- <div id="container"></div> -->

  <script src="three_95.js"></script>
  <script src="CopyShader.js"></script>
  <script src="EffectComposer.js"></script>
  <script src="RenderPass.js"></script>
  <script src="ShaderPass.js"></script>
  <script src="SubtractiveShader.js"></script>


  <script type="x-shader/x-vertex" id="stripesvertexshader">
        
         
         void main() {
             vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
             gl_Position = projectionMatrix * mvPosition;
         }

     </script>

     <script type="x-shader/x-fragment" id="stripesfragmentshader">
         
         void main() {
             gl_FragColor = vec4( 1.0, 1.0, 1.0, 0.5 );
             gl_FragColor = gl_FragColor
         }

     </script>

  <!-- Custom Scripts -->
     <script type="text/javascript" src="index.js"></script>

    </body>

当您计算对象的相对平移时,您从新位置 (newPosition) 中减去对象的当前位置 (spot[3])。

缩放对象时,不仅缩放了对象的大小,而且缩放了对象的位置(平移)。
这导致您计算的相对平移是错误的,因为它是基于对象的 "unscaled" 位置。

要解决您的问题,您还必须缩放存储的位置 (spot[3]):

newSpotSize = randomIntFromInterval( imageHeight*0.1, imageHeight*0.5 );
var scaleValue = generateScaleValue( spot[4], newSpotSize );
spot[0].geometry.scale( scaleValue, scaleValue, 1 ); // no change in scale for z
spot[4] = newSpotSize;
spot[3].x *= scaleValue;
spot[3].y *= scaleValue;

查看示例,其中我将建议的更改应用于您的原始代码:

var container, renderer, scene, camera;
var gridComposer, finalComposer;
var container = document.body;

var frustrumWidth, frustrumHeight;
var frustrumSize = 1000;
var aspect; // = window.innerWidth / window.innerHeight;
var zoom = 0.5;
var imageWidth, imageHeight;

var width, height;

// Light Spot
var spot;



function init() {

    width = window.innerWidth;
    height = window.innerHeight;

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.setClearColor(0x000000);

    aspect = window.innerWidth / window.innerHeight;
    camera = new THREE.OrthographicCamera( frustrumSize * aspect / - 2, frustrumSize * aspect / 2, frustrumSize / 2, frustrumSize / - 2, 0, 2000 );
    camera.position.set( 0, 0, 100 );
    camera.zoom = zoom;
    camera.updateProjectionMatrix();

    frustrumWidth = (frustrumSize * aspect);
    frustrumHeight = frustrumSize;

    imageWidth = (frustrumWidth * 2);
    imageHeight = (frustrumHeight * 2);


    ///////////////////////////
    // Create the LIGHT spot //
    ///////////////////////////

    scene = new THREE.Scene();
    
    var opacity = 0.7;
    var material = new THREE.MeshBasicMaterial({ transparent: true, opacity: opacity, color: 0xffff00 });
    var spotSize;
    spotSize = 200;
    var geometry = new THREE.PlaneBufferGeometry(spotSize, spotSize);
    geometry.dynamic = true;
    var z = 1.01;
    var startPosition = chooseAWindowPosition( spotSize );
    startPosition.z = z;
    geometry.translate( startPosition.x, startPosition.y, startPosition.z );
    var fading = true;
    spot = [ new THREE.Mesh(geometry, material), fading, opacity, startPosition, spotSize ];
    scene.add(spot[0]);
    

    ////////////////////////
    // Create AxesHelpers //
    ////////////////////////

    // top left
    var axes1 = new THREE.AxesHelper( 100 );
    axes1.geometry.translate( -(imageWidth/2)+10, (imageHeight/2)-10, 0.01 );
    scene.add( axes1 );

    // top right
    var axes2 = new THREE.AxesHelper( 100 );
    axes2.geometry.translate( (imageWidth/2)-10, (imageHeight/2)-10, 0.01 );
    scene.add( axes2 );

    // bottom left
    var axes3 = new THREE.AxesHelper( 100 );
    axes3.geometry.translate( -(imageWidth/2)+10, -(imageHeight/2)+10, 0.01 );
    scene.add( axes3 );

    // bottom right
    var axes4 = new THREE.AxesHelper( 100 );
    axes4.geometry.translate( (imageWidth/2)-10, -(imageHeight/2)+10, 0.01 );
    scene.add( axes4 );

    // middle
    var axes5 = new THREE.AxesHelper( 100 );
    scene.add( axes5 );

    container.appendChild( renderer.domElement );
    render();
    
}

function randomIntFromInterval(min,max) { // min and max included
    return Math.floor(Math.random()*(max-min+1)+min);
}

function generateTranslationValues( beginPosition, endPosition ) { // generates the translate() values needed to move from one position to another
    var xDifference = endPosition.x - beginPosition.x;
    var yDifference = endPosition.y - beginPosition.y;
    var translateValues = new THREE.Vector3( xDifference, yDifference, 0 );
    console.log("beginPosition:");
    console.log(beginPosition);
    console.log("endPosition:");
    console.log(endPosition);
    console.log("translation values:");
    console.log(translateValues);
    return translateValues;
}

function generateScaleValue( origSpotSize, newSpotSize ) { // generates the scale values needed to rescale from one spot size to another
    scaleValue = newSpotSize / origSpotSize;
    console.log("Start size: " + origSpotSize);
    console.log("End size: " + newSpotSize);
    console.log("Scale value: " + scaleValue);
    return scaleValue;
}

function chooseAWindowPosition( spotSize ) {
    var position;
    var x;
    var y;
    x = randomIntFromInterval( -imageWidth / 2, imageWidth / 2 );
    y = randomIntFromInterval( -imageHeight / 2, imageHeight / 2 );
    position = new THREE.Vector3( x, y, 0 );
    console.log( "-imageWidth / 2 is" +  (-imageWidth / 2) );
    console.log( "imageWidth / 2 is" +  (imageWidth / 2) );
    console.log( "-imageHeight / 2 is" +  (-imageHeight / 2) );
    console.log( "imageHeight / 2 is" +  (imageHeight / 2) );
    console.log( "spotSize is: " + spotSize );
    console.log("position is:");
    console.log(position);
    return position;
}

function render() {
    renderer.render( scene, camera );
    requestAnimationFrame( render );
    updateLightSpot();
}

function updateLightSpot() {
    var fading = spot[1];
    if ( fading ) {
        spot[0].material.opacity-=0.007;
    } else { // if not fading
        spot[0].material.opacity+=0.007;
    }
    var opacityLimit = spot[2];
    var newFadeValue;
    if ( spot[0].material.opacity >= opacityLimit ) {
        spot[0].material.opacity = opacityLimit;
        newFadeValue = true;
        spot[1] = newFadeValue;
    } else if ( spot[0].material.opacity <= 0 ) {
        // >>> SCALING SECTION <<<
          var newSpotSize;
            // >>> FIXED SCALE <<<
        //newSpotSize = 200;
        //spot[4] = newSpotSize;
            // >>> DYNAMIC SCALE <<<
        newSpotSize = randomIntFromInterval( imageHeight*0.1, imageHeight*0.5 );
        var scaleValue = generateScaleValue( spot[4], newSpotSize );
        spot[0].geometry.scale( scaleValue, scaleValue, 1 ); // no change in scale for z
        spot[4] = newSpotSize;
        spot[3].x *= scaleValue;
        spot[3].y *= scaleValue;

        // >>> POSITIONING SECTION <<<
        var newPosition;
            // >>> FIXED POSITION <<<
        newPosition = new THREE.Vector3( 0, 0, 0 );
        //var translateValues;
        //translateValues = generateTranslationValues( spot[3], newPosition );
        //spot[0].geometry.translate( translateValues.x, translateValues.y, translateValues.z );
        //spot[3] = newPosition;
            // >>> DYNAMIC POSITION <<<
        newPosition = chooseAWindowPosition( newSpotSize );
        var translateValues;
        translateValues = generateTranslationValues( spot[3], newPosition );
        spot[0].geometry.translate( translateValues.x, translateValues.y, translateValues.z );
        spot[3] = newPosition;
        newFadeValue = false;
        spot[1] = newFadeValue;
    }
}

init();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/95/three.js"></script>
<script type="x-shader/x-vertex" id="stripesvertexshader">
void main() {
    vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
    gl_Position = projectionMatrix * mvPosition;
}
</script>

<script type="x-shader/x-fragment" id="stripesfragmentshader">   
void main() {
    gl_FragColor = vec4( 1.0, 1.0, 1.0, 0.5 );
    gl_FragColor = gl_FragColor
}
</script>