Spinning item using a randomized matrix in Three.js

I'm in the process of creating a 3D die using Three.js that will rotate randomly when clicked, but I'm struggling to update the axis values properly. Here's where I'm currently at:

<style type="text/css" media="screen">
    html, body, canvas {
        margin: 0;
        padding: 0;
        background: #4e6171;
        color: black;
    }
    canvas {
        width: 100%;
        height: 100%;
    }
</style>

<body onload="animateScene();">
  <div id="container"></div>
  <script type="text/javascript" src="js/three.min.js"></script>
  <script type="text/javascript" src="js/Detector.js"></script>
  <script type="text/javascript">
    if (!Detector.webgl) Detector.addGetWebGLMessage();
  </script>
  <script type="text/javascript" src="js/TrackballControls.js"></script>
  <script type="text/javascript" src="js/setup.js"></script>


<script type="text/javascript">

function animateScene() {
    var objectX = Math.floor(Math.random() * 20);
    var objectY = Math.floor(Math.random() * 20);
    var objectZ = Math.floor(Math.random() * 20);


    var radius = 30;
    radius *= 1;

    var material = new THREE.MeshBasicMaterial({
        color: 0xe2e2e2,
        transparent: true,
        opacity: 1
    });

    var geometry = new THREE.IcosahedronGeometry(radius, 0);
    var object = new THREE.Mesh(geometry, material);
    var edges = new THREE.EdgesHelper(object, 0xffffff);

    edges.material.linewidth = 2;

    scene.add(object);
    scene.add(edges);
    scene.add(new THREE.AxisHelper(100));

    object.rotation.x = objectX;
    object.rotation.y = objectY;
    object.rotation.z = objectZ;

    controls.enabled = false;

};

</script>
<button class="button" onclick="object.updateMatrix();">Generate</button>
</body>

My goal is to click on the object and have it animate a rotation with new random axis coordinates. However, I'm currently encountering an "object is undefined" error.

I couldn't get a fiddle working, but you can find a link here.

Any assistance would be greatly appreciated. Thank you.

Answer №1

Upon close inspection, I have identified two key issues in this scenario:

  1. The "object" variable is limited to the scope of the animateScene() function, leading to the "object is undefined" error. To resolve this, consider defining object (using "var object") outside of the function for global accessibility, or attach the onClick callback within animateScene itself.
  2. Even if you address the scoping concern, the object will not rotate due to rotating just once in animateScene(). For rotation to occur, new random values for X, Y, and Z need to be generated, followed by a call to object.updateMatrix().

Trust that this explanation proves beneficial!

Answer №2

BREAKTHROUGH

Last night, a breakthrough occurred allowing me to achieve exactly what I had been seeking. A new function was created within the scene to generate fresh x and y values which are then used to update the matrix. The animation was managed using tween.js. Additionally, the click event was bound inside the animateScene function rather than being placed in an onClick event externally.

A special thanks to Tim for providing valuable guidance throughout this process.

<body onload="animateScene();">
<div id="container"></div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/three.min.js"></script>
<script type="text/javascript" src="js/tween.min.js"></script>
<script type="text/javascript" src="js/Detector.js"></script>
<script type="text/javascript">
    if (!Detector.webgl) Detector.addGetWebGLMessage();
</script>
<script type="text/javascript" src="js/TrackballControls.js"></script>
<script type="text/javascript" src="js/setup.js"></script>
<script type="text/javascript">

    var object

    function animateScene() {


        var radius = 30;
        radius *= 1;

        var material = new THREE.MeshBasicMaterial({
            color: 0xe2e2e2,
            transparent: true,
            opacity: 1
        });

        var geometry = new THREE.IcosahedronGeometry(radius, 0);
        var object = new THREE.Mesh(geometry, material);
        var edges = new THREE.EdgesHelper(object, 0xffffff);

        edges.material.linewidth = 2;

        scene.add(object);
        scene.add(edges);
        scene.add(new THREE.AxisHelper(100));

        controls.enabled = false;


        function rollDice() {

            var x = Math.floor(Math.random() * (14 - 7) + 7);
            var y = Math.floor(Math.random() * (14 - 7) + 7);


           var tween = new TWEEN.Tween(object.rotation)
              .to({ x, y }, 500)
              .start();

           animate();

           function animate() {
              requestAnimationFrame(animate);
              TWEEN.update();

           }

        }

        $( "#click" ).click(rollDice);

    }



</script>
<button class="button" id="click">Generate</button>
</body>

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

Having trouble changing a state from a class component to a function component in React

I've been updating my React projects by converting all my classes to functions. However, I encountered an issue where ESLint is reporting a parsing error in my code. Oddly enough, if I remove just one line, the error disappears. Here's the snippe ...

Display a specific template in the detail grid of the Kendo Grid depending on certain conditions

I've been using the Kendo Grid and it's been working well for me. I have a requirement to check each row in my grid to see if it contains a specific value, and based on that, bind data using different templates. Is this feasible? Below is the cod ...

Node.js and JavaScript promises are not pausing for the sequelize query to complete

The promise mentioned below should ideally return the customer and blox slot as part of the booking record in the second .then(). However, it seems that addCustomer and addBooking have not been executed yet. When I added await to addBooking or addCustomer ...

How can one display blog data (stored as a PDF) from a database alongside other different results (stored as

I have successfully displayed a PDF file from my database as a blob using the header("Content-type:application/pdf") method. Now, I am looking to also display some additional string results along with this PDF file. Is it feasible to achieve this while d ...

Is there a way to successfully include an apostrophe in a URL?

I am currently utilizing Node.js: var s = 'Who\'s that girl?'; var url = 'http://graph.facebook.com/?text=' + encodeURIComponent(s); request(url, POST, ...) This method is not functioning as expected! Facebook seems to be c ...

What is the best way to identify different directives within the same $scope?

When it comes to calling directive functions from controllers, I follow this approach: function myControllerFunction = function () { $scope.highlight(); } The highlight() function is defined within the directive itself. But what if there are two dif ...

"Trouble arose when I tried to incorporate additional functions into my JavaScript code; my prompt feature is not

As a beginner in HTML and JS coding, I am working on creating a page that prompts user input for a name and then executes animations using radio buttons. However, after adding functions for radio button changes, my prompt is no longer functioning properly. ...

having difficulty with executing ajax post within a JavaScript function

While working on my project, I encountered a small issue. I am able to read the HTML image value and pass it to a JavaScript method successfully. However, when trying to pass this value via AJAX POST to the controller, an unexpected error occurs. The con ...

What is the best way to determine whether a YouTube video permits embedded playback?

When working with user-generated content, it's important to note that YouTube channels may restrict their videos from being played in an embedded player. In order to provide a better user experience, I need to detect the specific reason why a video ca ...

Issues with loading NextJS videos can occur when accessing a page through a link, as the videos may fail to load without

Issue Greetings. The problem arises when attempting to load muse.ai videos on-page, specifically when accessing the page with a video embedded through a NextJS link. To showcase this issue, I have provided a minimal reproducible example on StackBlitz her ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

Attempting to run the npm install command led to encountering a SyntaxError with an

Recently, I made some alterations to my npm configuration and ever since then, I have been consistently encountering the same error whenever I try to install various packages. It seems that due to a personal mistake in changing the npm settings, I am now u ...

A guide on accessing the JSON file data using jQuery

Currently, I am attempting to retrieve data from an API. Essentially, there is a URL that returns JSON data which I need to utilize. var url = "http://212.18.63.135:9034/played?sid=1&type=json"; $.getJSON(url, function(data) { console.log(data) ...

Is it possible to remove an element from a data structure in a web application using an HTTP command?

Apologies for the confusing title, I struggled to find a better way to describe it. Imagine sending a GET request to an API and receiving this data: { {id: 1, name: "John Doe", tags: ["Apple", "Orange", "Pear"]}, {id: 2, name: "Jane Doe", tags: [ ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

Unleashing the full potential of ajax through endless scrolling performance

Recently, I implemented an infinite scroll feature on my website's index page by making ajax requests to retrieve a JSON containing 40 objects. Then, I add them using a JavaScript loop. However, I've noticed that it slows down the site at times. ...

Loading information in a directive by utilizing promises in a service with AngularJS

Can anyone lend a hand? I've been struggling to solve this issue. I created a directive (see below) to display a pre-written ul-list on a page using html data fetched asynchronously from a database server. Both the Directive and The Service are funct ...

Display PDF file retrieved from the server using javascript

I am currently working on a web application using JavaScript, jQuery, and Node.js. I need to receive a PDF file from the server and display it in a new browser window. While I believe I have successfully received the file on the client side (the window sh ...

Conceal / Modify / Incorporate a picture

My ultimate goal is to have a hidden box and image that will be revealed based on the result of other functions. The box should change its background color, display an image, and switch images depending on the function called. I am facing two issues with ...

Troubleshoot: Issue with Multilevel Dropdown Menu Functionality

Check out the menu at this link: The issue lies with the dropdown functionality, which is a result of WordPress's auto-generated code. Css: .menu-tophorizontalmenu-container { margin: 18px auto 21px; overflow: hidden; width: 1005px; ...