Object responds to mouse click by rotating and moving through animation

Exploring the possibilities of three.js

I'm attempting to create an animation (rotation/movement) for an object upon a mouse click event, however, I am not achieving the desired animation effects.

Below is the code snippet that I have implemented. Could it be that I am using render excessively?

        document.addEventListener( 'mousedown', clickMe, false );
        render();

        function clickMe() {
            rotation();
            render();   
        }

        var gltfModel;

        function rotation() {
            var rotationAnimation = 5 * (Math.PI / 180);
            gltfModel.rotation.x += rotationAnimation;
            render();       
        }

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

If I insert 'requestAnimationFrame(rotation);' within the rotation function:

        function rotation() {
            requestAnimationFrame(rotation);
            var rotationAnimation = 5 * (Math.PI / 180);
            gltfModel.rotation.x += rotationAnimation;
            render();       
        }

The gltfModel continues to spin endlessly, and every time I click, the speed doubles.

Here is the complete code:

       // Complete code provided here
    

Is this achievable with EventDispatcher? If so, what would be the approach? https://threejs.org/docs/#api/en/core/EventDispatcher

However, my preference leans towards the initial method discussed.

Answer №1

Indeed, you only need to execute the render function once. Therefore, you can remove those calls from within both the rotation() and clickMe() functions, placing them after

document.addEventListener( 'mousedown', clickMe, false );
.

Nevertheless, by following this approach, the object will only rotate once with each click. Assuming your goal is to continuously rotate the object while holding down the mouse button.

If that is the case, you can simply set a boolean flag on mousedown.

Within the clickMe function, consider implementing something like:

function clickMe() {
  rotating = true; // ensure this variable is globally declared
}

Subsequently, in the render function, you may include the following logic:

function render() {
  if (rotating) {
    var rotationAnimation = 5 * (Math.PI / 180);
    gltfModel.rotation.x += rotationAnimation;
  }
  renderer.render(scene, camera);
}

Lastly, remember to attach a mouseup listener to halt the object's rotation when releasing the mouse button.

function handleMouseUp() {
  rotating = false;
}

document.addEventListener('mouseup', handleMouseUp);

Answer №2

If you're looking to add a spinning box feature to your gltf model, here's a basic code sample to help you get started. Remember that using the render method in your functions might not be necessary, so take a look at some simple scene examples for guidance.

For more information and detailed instructions on creating a scene with Three.js, check out this link.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/101/three.min.js"></script>
<script> 
    var box;
    var isMouseDown = false;
    var rotateSpeed = 0;

    init();
    animate();

    function init() {

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

        camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.25, 20);
        camera.position.set(5,5,5);
        camera.lookAt(new THREE.Vector3(0,0,0));

        scene = new THREE.Scene();

        light = new THREE.HemisphereLight(0xbbbbff, 0x444422);
        light.position.set(0, 1, 0);
        scene.add(light);
        
        var geometry = new THREE.BoxBufferGeometry(1, 1, 1);
        var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
        box = new THREE.Mesh(geometry, material);
        scene.add(box);

        renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(window.innerWidth, window.innerHeight);
        container.appendChild(renderer.domElement);

        window.addEventListener('mousedown', () => isMouseDown = true,false);
        window.addEventListener('mouseup', () => isMouseDown = false,false);
        
        animate();

    }

    function animate() {

        requestAnimationFrame(animate);

        if(isMouseDown) rotateSpeed += 0.001;
        else rotateSpeed /= 1.01;
        box.rotation.y += rotateSpeed;

        render();

    }
    
    function render() {

        renderer.render(scene, camera);

    }
</script>

</html>

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

Choose the span element that is contained within multiple div elements

Is there a way to target a specific span tag and change the text color to white without using IDs? I am trying to modify the CSS of the friend section on a page but cannot add any IDs. This is for the friend section on the website younow. <div id="left ...

Sending data from a Flask application written in Python to a JavaScript file using AJAX for seamless integration

As I am still in the learning process, please bear with me. I have been making attempts to find solutions, but often encounter issues when sending data of type="POST" from JavaScript to Flask using AJAX. This is the code snippet from my app.py f ...

Rotating the icon in Bootstrap Accordion upon opening

I am trying to customize a Bootstrap 4 accordion by conditional rotating the icon to point up when it is open and back down when closed. I managed to achieve this using CSS, but now I need to implement it conditionally based on active states rather than ev ...

Is {{@index}} an even or odd number in Handlebars: A Step-by-Step Guide

I'm currently cycling through an array, and I'd like to adjust the background color of the div based on whether the current index is odd or even. Unfortunately, when I try to use {{@index}} within an if statement in Handlebars, like so: {{#each ...

Tips for hiding the bottom bar within a stackNavigator in react-navigation

I am facing a challenge with my navigation setup. I have a simple createBottomTabNavigator where one of the tabs is a createStackNavigator. Within this stack, I have a screen that I want to overlap the tab bar. I attempted to use tabBarVisible: false on th ...

Error: Uncaught TypeError - Unable to access the 'handleClick' property of undefined within a forEach loop

I came across the following code snippet articles_list.jsx import React from 'react'; import './articles_list.css'; export default class ArticlesList extends React.Component { constructor(props) { super(props); this.state ...

What is the best way to confirm if the elements in an array are in consecutive order?

Is there a way to determine if an array's members are consecutive? For instance, the array [1,3,4,5,6] is not considered consecutive because it is missing the number 2 in the sequence. Which JavaScript array methods can be used to check for this type ...

Find unique numbers within a specified range using NodeJS

I need to update my arts on an NFT test via OpenSea API, but I'm facing an issue where the numbers are being repeated. Is there a way to select a number within a range that does not repeat? Here is my current code: const opensea = require("opense ...

Encountering a problem when trying to assign a value to a file/image input field using Vue Formulate

Having trouble setting the initial value for the image input field? The documentation suggests providing an array of objects with URLs (link to docs). I've followed the same format for other fields like 'text' and 'email', which w ...

Examining whether an ajax call was not initiated within an Angular application

Is there a way to verify that an ajax request has not been made using Angular's $httpBackend? I attempted to use verifyNoOutstandingRequest() but it doesn't seem to be triggering test failures in version 1.1.5. Here is more information about the ...

Effective methods for eliminating timezone in JavaScript

I need to display the time and format {{transaction.submitTime | date:'yyyy-MM-dd HH:mm:ss Z'}} Currently, it displays 2015-04-23 02:18:43 +0700 However, I would like to show the time without +0700, where the hour will be incremented by 7. Is ...

"Enhancing communication with PHP-powered private messaging through AJAX technology

Hey, I'm interested in creating a basic private messaging system using PHP, MySQL, JavaScript, and possibly AJAX. However, I'm unsure of how to begin. Can anyone recommend any user-friendly tutorials for building one? It doesn't have to be e ...

A guide on verifying a phone number using just one character

I am looking to validate a phone number with only one character being allowed. For example, the format should be XXX-XXXXXXX where "-" is the only allowed character. Below is my validation function: function validatePhoneNumber() { if(addform.staff_m ...

Modify/Adjust/Move the image uploaded by the user in VueJS before transferring it to an aws s3 bucket

Can you resize images in vuejs using vanilla js? I've managed to upload an image and send it to my s3 bucket using vue, but I'm struggling to figure out how to transform an image within vuejs and display it. Document.querySelector doesn't se ...

The utilization of "startIcon" and "endIcon" from the <Button/> API of Material-UI is restricted

I've been trying to work with this React code for a single component, but no matter what I do, I keep getting the same warning. I even tried copying and pasting the example, but the warning persists and the icon is not showing up. Can someone please a ...

Ways to access elements and their associated values in a JavaScript Array

I'm facing a challenge with a JavaScript array where I need to extract teams (Team A, Team B) and organize them into one array while preserving their order. See below for the current output of the array, as well as the JS code provided and the expecte ...

I'm having trouble getting my innerHTML command to update anything on the webpage, and the reason is eluding me

Below is the code snippet provided: <div id="js"><button onclick="document.getElementById('js').innerHTML=('<form> <input type=text name=tick1></input> <input type=text name=tick2></input> ...

TPL operating on a List that is stocked with merchandise

I am facing an issue with the following code snippet: {[displayDate(dateRelease);]} Every model available in the store comes with a "dateRelease" property. I want to retrieve that date and format it using my displayDate() function before displaying it. ...

Navigating in React Navigation: Techniques to Directly Access a Specific Index in a Datasource

I am a beginner at React Native and I have been working on developing a simple recipe app. Everything was going well until I reached the point where I needed to navigate to a specific recipe from my dataset. I am looking to create a singleRecipe.js compone ...

retrieve undefined value from redux state in a React Native application

Received the data in reducer but encountering issues accessing it in the component. Below is the connection code: const mapStateToProps =state => { return { name:state.fbLogin.name } } function mapDispatchToProps(dispatch){ ...