What causes unpredictable script behavior when both scale and positioning are constantly changing?

For quite some time, I've been attempting to pinpoint a bug that causes erratic behavior when both the scale and position of a square in the script below are dynamic. The purpose of this script is to have a square fade up and down while changing positions and scales across the screen. If either the scaling or positioning is fixed, or even both, then everything works as expected - the square fades at regular intervals in different positions or scales (or with both fixed). However, if both scaling and position are dynamic, then there are times when the square doesn't appear on the screen at all, and most of the time it barely shows up. What could be causing this strange behavior?

I've divided the snippet below into sections for dynamic and fixed scaling/positioning so you can experiment and see for yourself what's going on. Currently, I have them set to dynamic so you can observe the intermittent behavior I'm facing. Your insights after taking a look would be greatly appreciated!

UPDATE: In case you prefer working through it differently, here's a fiddle link for you to delve into as well.

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;

// Rest of the JavaScript code continues...
    
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>

Answer №1

When determining the relative translation of an object, it involves subtracting the current position of the object (spot[3]) from the new position (newPosition).

Scaling an object affects not only its size but also its position (translation). This leads to miscalculations in the relative translation as it is based on the "unscaled" position of the object.

To resolve this issue, you need to scale the stored position (spot[3]) as well:

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;

Here's an example where the suggested changes have been applied to the original code:

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;
  
// Functions and logic implementation omitted for brevity

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>

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

There is an issue with Node/Express not accurately updating the data model

I recently went through a tutorial on creating a RESTful API with Node.js and MongoDB. While it worked well overall, I encountered a few issues. My Player model is as follows: var player = new mongoose.Schema({ name: String, email: String, score: String } ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Exploring the world of form interactions in Angular: A guide to creating dynamic element communication

I have created a form using Angular, and I want to display a specific value in my input field when an element is selected from the dropdown. Additionally, since the values in the dropdown are fetched from a server, I want to show a corresponding label for ...

Transmitting data using JavaScript to Spring server

I am facing a challenge of uploading an image to a server using Spring. The code snippet I am using to get the file is as follows: var file = $("#form-field-photo").get(0).files[0]; I have attempted several methods to post it, but so far, all my attempts ...

How can you verify the correctness of imports in Typescript?

Is there a way to ensure the validity and usage of all imports during the build or linting phase in a Typescript based project? validity (checking for paths that lead to non-existent files) usage (detecting any unused imports) We recently encountered an ...

Struggling to make the javascript function compatible with the drop-down menu

I'm encountering issues with making my JavaScript work properly alongside my HTML. Specifically, I want the "activity" drop-down box to function in conjunction with the "city" drop-down box. For instance, if I choose "Brisbane" and then select an acti ...

Using Node.js to efficiently parse JSON data into customizable PUG templates

I have a challenge where I am parsing JSON data into elements called homeCards. To achieve this, I use Axios to request the JSON data and then utilize a for loop to cycle through it. Inside my Axios function, I extract the fields I need and store them in v ...

The functionality of document.elementFromPoint(x, y) seems to be faulty in accurately identifying child elements

I've been trying to retrieve the element over which a "drop" event occurs, but I keep getting unexpected results. It consistently returns parent elements instead of the actual child element where the dragged element is dropped on. For a full code exa ...

I am interested in utilizing props to send a variable to the view

Looking for assistance with passing the variable tmp_sell to my view. Here is the code: <p @tmp_sell="getTmpSell" >?</p> <input ref="q_subtotal" placeholder="Subtotal" @tmp_sell="getTmpSell" i ...

When you hover over an image, both the image's opacity and the color of the title beneath it change. However, if the title expands to two lines, it messes up

I am currently working on a project where I have an image and a title displayed below the image. My goal is to change the color of the text when hovering over the image, as well as adjust the opacity of the image. Additionally, when hovering over the title ...

How can I implement a feature in Django where clicking on a form will automatically clear the initial text within it?

One common feature seen on websites is the username form box that initially displays "username" as a placeholder text. Upon clicking on the box, the word "username" disappears to allow users to input their own username. Appreciate it! ...

Choose the list item by identifying the corresponding unordered list

Is there a way to target the second li element within an ul list like this: HTML <ul> <li></li> <ul> <li>This one is what I need to select</li> </ul> </ul> ...

Navigating Crossroadsjs Routing: A Beginner's Guide

After exploring various resources to understand how crossroads works, I stumbled upon a question on Stack Overflow that resonated with my struggles. However, despite spending hours trying to implement it, nothing seems to be working. The documentation on i ...

What is the best approach to managing this scenario where the document is ready?

Just a quick question. I have several JavaScript functions written in this format: var app={ start:function(){ //do something and call calculate }, //end start calculate:function(){ //do more stuff } //end calculate }; //en ...

Watching for changes in a callback function - Angular 2

I'm currently working on implementing a callback function within a service class that needs to send data back to the component class. ChatComponent.ts export class ChatComponent implements OnInit { constructor( public _chatService : ChatService) ...

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

What could be the reason for not seeing any console.log output while executing findOne using Mongoose?

My goal is to query my MongoDB database using Mongoose. I am searching for the string 13 in the field eClassSegment within the collection eclasses. When I run the code, something gets printed in the console. Why is that? Here is the code I am using: var ...

what is the best way to activate components within a directive template externally?

Having trouble accessing DOM elements outside the app.js that are created by the directive in AngularJS. What is the best approach to solve this issue? I am new to AngularJS and appreciate any suggestions. app.directive('myMenu', function() { ...

leveraging the default browser behavior for the href and target attributes within an <a> element in Angular 2

How can the behavior of a simple anchor tag in Angular 2 be implemented without being overridden by the routing module? <a href="some url" target="_whatever"> It is crucial to prevent the routing module from highjacking the URL using the base href. ...

JQuery Mobile Navigation with Bootstrap 3 Sidebar on the Go

While using RoR, I encountered a baffling issue. I have created a new navbar with a sidebar that only displays on mobile and not on desktop. The Turbolink is functioning properly. <%= javascript_include_tag 'application', 'data-turboli ...