Using Three.js to control the visibility of a basic mesh

I am relatively new to Three.js and WebGL, but I am determined to improve my skills in this area. Could you please review my code where I have successfully found a solution to a seemingly simple problem that I challenged myself with?

THE ISSUE I FACED (which took longer than expected to resolve): How can I animate a basic 400 x 400 PLANE MESH from a starting position of y=500 (below the browser window) to a target position of x=0, y=0, z=0 (center of the browser window) without relying on Tween.js? While Tween.js is efficient for simple movements in Three.js, I wanted to learn by finding my own solution. I spent hours researching various solutions on StackOverflow and Mr. Doob's GitHub repository, but none fully met my requirements: a straightforward vertical animation starting out of the frame and ending in the center of the browser window.

THE SOLUTION I IMPLEMENTED:

function animate() {
    var newPos = plane.position.y;
    plane.translateY(4);
    function stopHere () {
        if (newPos >= 0) {
            plane.position.set(0, 0, 0);
            var stopPlane = plane.position.y = 0;
        }
    }
    requestAnimationFrame(stopHere);
}

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

I have included the two functions responsible for accomplishing the task. Is there anything concerning or inefficient in this approach? My reasoning is that

requestAnimationFrame

cannot be inside the render() function, as it needs to be within the scope of the nested function ('stopHere') inside

animate();

I faced challenges while using the following approach:

objMesh.geometry.applyMatrix( new THREE.Matrix4().makeTranslation(1, 0.1, 0.1));

Despite struggling with what seemed like a simple problem for over a week, I am confident that my solution is functional. I utilized the applyMatrix sub-class method to achieve the desired outcome. I am seeking feedback to ensure I am learning Three.js correctly and avoiding bad practices. Can anyone identify any areas of concern or improvements needed in my code? Thank you.

ksqInFlight

Answer №1

As a seasoned individual, my strategy entails incorporating the following code snippet into your requestAnimationFrame loop:

function fnloop() {
  var dy = Math.min(Math.abs(plane.position.y), .01); // maximum movement
  if (Math.abs(dy) >= .000001) {
    if (plane.position.y > 0) dy = -dy; // downward movement if above
    plane.position.y += dy; // adjust position
    if (Math.abs(plane.position.y) < .000001) alert("Mission accomplished!");
  }
  renderer.render(scene, camera);
  requestAnimationFrame(fnloop);  
}

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

Adjust the styling of selected elements when their values are changed

I am attempting to modify the background color based on the selected value that is returned. However, my current code doesn't seem to be working as expected: <script> $(document).ready(function() { $('#assessments').change(functi ...

Hover over parts of an image to bring attention to them

I am interested in developing a webpage featuring a black and white image of 5 individuals. When hovering over each person, I would like them to illuminate and display relevant information in a dialog box next to them. Do you have any tips on how I can ac ...

What is the process for generating an attribute in a system?

If I want to create an element using plain JavaScript, here is how I can do it: var btn = document.createElement('button'); btn.setAttribute('onClick', 'console.log(\'click\')'); document.body.appendChild( ...

How to incorporate Mixin in your Nuxt template

I'm having trouble utilizing the mixin function in my template. Although Vue documentation states that mixins and components are merged, I am unable to call the function. getImage is not a function Mixin export default { data() { return { ...

How can I efficiently fetch data from Firebase, manipulate it through computations, and present it using React Hooks?

I am currently working on retrieving multiple "game" objects from Firebase Storage, performing statistical calculations on them, and then presenting the game statistics in a table. Here is an overview of my code structure: function calculateTeamStatistics( ...

D3 not distinguishing between bars with identical data even when a key function is implemented

When attempting to create a Bar chart with mouseover and mouseout events on the bars using scaleBand(), I encountered an issue. After reviewing the solution here, which explains how ordinal scale treats repeated values as the same, I added a key to the dat ...

What is the reason JSON.parse fails to convert a string into a JSON object?

I attempted to convert a string into a JavaScript object using JSON.parse, however, it seems to be unsuccessful. After trying various methods, I did not receive any output in the console.log and no error messages were displayed. JSON.parse(`{'exp&apo ...

Creating a filter and word replacement method in Android Studio is a useful tool for implementing text transformations

Hello there! I am currently working on developing an application that can recognize voice and convert it into text. I have successfully implemented the conversion and comparison features, but there are specific words that I need to modify or replace in the ...

Unlocking the Secret Code

Presenting the question: checkPassword([["Peter", "P"], ["Sarah", "S"], ["Ethan", "R"]], {"Peter": "P", "Sarah": "Q", //"Ethan":"E"}) ...

Issue with Pagination functionality when using Material-UI component is causing unexpected behavior

My database retrieves data based on the page number and rows per page criteria: const { data: { customerData: recent = null } = {} } = useQuery< .... //removed to de-clutter >(CD_QUERY, { variables: { input: { page: page, perPag ...

Enhance communication system by optimizing MySQL, JavaScript, and PHP chat functionality

I have created a chat application using Javascript, PHP, and MySQL for two users. Every 3 seconds, it makes an AJAX request to a PHP file to retrieve messages from the database and update the page. Currently, the PHP query used is: SELECT * FROM tmessages ...

What is the solution for resolving an Element that implicitly has said it has an 'any' type as the expression of type 'string' cannot be used to index the type?

Having some trouble with TypeScript in my React project and encountering this error message. Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ paymentMethod ...

The z-index property in jQuery dialog does not seem to function properly when used within an

When using bootstrap with jQuery dialog, I encountered a strange issue. If the z-index of the dialog is set to 1 or higher in a standalone script, everything works fine. However, when the same script is called inside an iframe, the dialog ends up appearing ...

Creating a unique Angular filter involves combining different techniques and functionalities to tailor

Hey there! I'm just diving into the world of Angular JS and I'm looking to filter any Twitter text that comes back containing a hashtag, and turn that word into a clickable link. For example: If the returned twitter text is "The quick brown #f ...

Error in React Native JS: Cannot call the `map` function on variable `l`

Recently diving into the world of Js and React, I am tasked with creating an application for Macronutrients in my second semester project. The challenge I'm facing is incorporating a Pie Chart that displays the values from my state. To implement the ...

Can you explain the purpose of the .json() function in Angular2?

Can you explain the purpose of the .json() function within http requests in Angular2? Here is an example code snippet: this.http.get('http://localhost:8080/getName') .subscribe(res => this.names = res.json()); Is it correct to assume that t ...

Issues with utilizing Fetch API and JSON Data

I'm encountering some difficulties while trying to interact with my json file. I am using the fetch API to retrieve my json file but, unfortunately, when I log the response to the console, I don't see any data returned. Instead, what appears is a ...

Customizing error messages in react-hook-form-mui: A step-by-step guide

I'm currently diving into the world of react-hook-form-mui library. The documentation provided for this project is quite brief, and I've been struggling to add a validation rule to my form field. Despite trying various methods, none seem to be ef ...

Displaying the output of a PHP script in an AJAX request

I am trying to display feedback from certain checks, like checking if a file already exists, after making an ajax call to upload a file using my script. However, for some reason, I can't get the response to show up. Why is the response not appearing? ...

AngularJs setPristine() not resetting the invalid status of a form

Is there anyone who can assist with the provided Plunker code? All you need to do is submit the form with just one required field filled out. This action will result in validation errors being displayed. When you reset the form by calling both setPristine ...