Move the object in Three.js by rotating it around the origin (0,0,0) in response to mouse

I am currently working with an object in Three.js that was created in Blender and imported into the Three.js format. My goal is to enable mouse rotation for this object. Any assistance on how to achieve this would be greatly appreciated! Thank you.

    function initialize(x, y, z, base, small, big, corners) {
    scene = new THREE.Scene();

    createMesh(x, y, z, base, small, big, corners);
    setupCamera();
    addLights();
    setupRenderer();
    var element = document.body.appendChild(renderer.domElement);
    element.style.marginLeft="300px";
    element.style.position="absolute";

    render();

}

function setupCamera() {
    camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
    camera.position.set(0, 3.5, 3);
    camera.lookAt(scene.position);
}


function setupRenderer() {
    renderer = new THREE.WebGLRenderer({ antialias: true});
    renderer.setSize(WIDTH, HEIGHT);
    renderer.setClearColor("white");
}
var mainMesh = null;
var mesh1 = null;
var mesh2 = null;
var mesh3 = null;

var meshGroup;
function createMesh(x, y, z, base, small, big, corners) {
    meshGroup = new THREE.Object3D();
    var loader = new THREE.JSONLoader();
    loader.load(base, function(geometry, materials) {
        mainMesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        mainMesh.scale.x = x;
        mainMesh.scale.y = y;
        mainMesh.scale.z = z;
        mainMesh.opacity=1;
        mainMesh.castShadow = false;
        var model = new THREE.Object3D();
        model.add(mainMesh);
        model.position.set(0,0,0);
        meshGroup.add(model);
    });
    loader.load(small, function(geometry, materials) {
        mesh1 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        mesh1.scale.x = x;
        mesh1.scale.y = y;
        mesh1.scale.z = z;
        mesh1.opacity=1;
        mesh1.castShadow = false;

        var model1 = new THREE.Object3D();
        model1.add(mesh1);
        model1.position.set(0,0,0);
        meshGroup.add(model1);
    });
    loader.load(big, function(geometry, materials) {
        mesh2 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        mesh2.scale.x = x;
        mesh2.scale.y = y;
        mesh2.scale.z = z;
        mesh2.opacity=1;
        mesh2.castShadow = false;

        var model2 = new THREE.Object3D();
        model2.add(mesh2);
        model2.position.set(0,0,0);
        meshGroup.add(model2);
    });
    loader.load(corners, function(geometry, materials) {
        mesh3 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        mesh3.scale.x = x;
        mesh3.scale.y = y;
        mesh3.scale.z = z;
        mesh3.opacity=1;
        mesh3.castShadow = false;

        var model3 = new THREE.Object3D();
        model3.add(mesh3);
        model3.position.set(0,0,0);
        meshGroup.add(model3);
    });

    scene.add(meshGroup);
}
function addLights() {
    var light;  // A light shining from the direction of the camera.
    light = new THREE.DirectionalLight();
    light.position.set(0,100,10);
    meshGroup.castShadow = false;
    meshGroup.receiveShadow = false;
    scene.add(light);   

}

function rotateMainMesh() {
    if (!mainMesh) {
        return;
    }
    //meshGroup.rotation.y -= 0.4* ( Math.PI / 180 );
}

function animate() {
    requestAnimationFrame(animate);
    rotateMainMesh();
    renderer.render(scene, camera);
}
initialize(0.5, 0.5, 0.5, "base.js", "small.js", "big.js", "corners.js");

Answer №1

If you're curious, I stumbled upon the solution here. In my particular scenario, the 'root' element had to be changed to 'group'

    var mouseDown = false,
    mouseX = 0,
    mouseY = 0;

function onMouseMove(evt) {
    if (!mouseDown) {
        return;
    }

    evt.preventDefault();

    var deltaX = evt.clientX - mouseX,
        deltaY = evt.clientY - mouseY;
    mouseX = evt.clientX;
    mouseY = evt.clientY;
    rotateScene(deltaX, deltaY);
}

function onMouseDown(evt) {
    evt.preventDefault();

    mouseDown = true;
    mouseX = evt.clientX;
    mouseY = evt.clientY;
}

function onMouseUp(evt) {
    evt.preventDefault();

    mouseDown = false;
}
var ee = document.body.appendChild(renderer.domElement);
ee.addEventListener('mousemove', function (e) {
    onMouseMove(e);
}, false);
ee.addEventListener('mousedown', function (e) {
    onMouseDown(e);
}, false);
ee.addEventListener('mouseup', function (e) {
    onMouseUp(e);
}, false);
var c=1;
var cc=3;
var ccc=3;
ee.addEventListener('wheel', function (e) {
    console.log(e.deltaY);
    if(e.deltaY>0){
    c=c*0.95
    cc=cc*0.95;
    ccc=ccc*0.95
    camera.position.set(c, cc, ccc);
    }else{
    c=c*1.05
    cc=cc*1.05;
    ccc=ccc*1.05
    camera.position.set(c, cc, ccc);}
});

function rotateScene(deltaX, deltaY) {
    group.rotation.y += deltaX / 100;
    group.rotation.x += deltaY / 100;
} 

Additionally, a zoom feature was implemented with the aid of this library here

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

Javascript in Chrome can be used to initiate and conclude profiling

Is there a way to activate the CPU Profiler in the Chrome developer window using a Javascript call? For example: chrome.cpuprofiler.start(); //perform intensive operation chrome.cpuprofiler.stop(); Currently, my only option is to manually click on "s ...

Expanding the number of buttons for <ul> in creating a responsive navigation system using Angular

My navigation consists of 8 items (li), and as the resolution shrinks, the items are pushed onto a new line. I am looking to implement a feature where if an item doesn't fit in the navigation anymore, a "MORE" dropdown button appears on the right side ...

When you hover over an image, its opacity will change and text will overlay

I am looking for a way to decrease the opacity and overlay text on a thumbnail image when it is hovered over. I have considered a few methods, but I am concerned that they may not be efficient or elegant. Creating a duplicated image in Photoshop with the ...

Construct a table from JSON data

I am having trouble generating a table from JSON data. It seems like there may be an issue with my link, but there could be something else going on as well. I am not seeing any data displayed in my table and the error message I am getting is: Cannot read ...

The attempt to perform a 'put' operation on the Cache with workbox and nuxt was unsuccessful

Encountering an unexpected error in my console while working on Nuxtjs version 2.15.7: https://i.sstatic.net/pvjv9.png https://i.sstatic.net/A3nrF.png Upon investigation, it seems to be related to the @nuxt/pwa module, even though I don't have it i ...

Encountering issues with activeClassName when implementing NavLink in TypeScript

Encountering an issue where I'm receiving the error message "Property 'activeClassName' does not exist on type IntrinsicAttributes" while attempting to utilize activeClassname on NavLink in a TypeScript project. See the code snippet below: i ...

Python/Selenium Issue: JS/AJAX Content Fails to Load when URL is Accessed

Currently, I am attempting to gather data from the following URL: The data that I am looking to extract is loaded dynamically, such as the Center Bore information. When accessing the link through a standard web browser, the content loads without any issue ...

Creating a line extending towards the raycaster using three.js

In my three.js project, I am using PointerLock controls to create a basic first person shooter game. I have implemented the following event listener function: function onDocumentMouseDown( event ) { var raycaster = new THREE.Raycaster(); mouse3D.norma ...

How to pass a String Array to a String literal in JavaScript

I need to pass an array of string values to a string literal in the following way Code : var arr = ['1','2556','3','4','5']; ... ... var output = ` <scr`+`ipt> window.stringArray = [`+ arr +`] & ...

Aggregate array based on specified criteria in ReactJS

Let's consider the following array data: array = [ { id: 1, count: 0.5 cost: 100 user: {id: 1, name: "John 1"}, type: {id: 1, name: "T1"}, period: {id: 1, name: "2021"} ...

Encountered an issue while trying to retrieve a value from an object within a

Reviewing the following JSON response: [ {"name": "Afghanistan", ...}, {"name": "country 2" ,...}, {"name": "country 3" ,...}, ] My goal is to extract only country names from t ...

Is the HTML5 type of button functioning properly, while the type of submit is not working as

Looking to validate a form before running a JavaScript function? Check out this code snippet: function updateMap() { //dummy } <form> <div class="group"> <input type="number" id="hour" min="0" max="23" required> <span cl ...

Enclosing Material UI's DataGrid GridActionsCellItem within a custom wrapper component triggers a visual glitch if showInMenu is enabled

Here is how my MUI DataGrid columns are structured: const columns = [ { field: "name", type: "string" }, { field: "actions", type: "actions", width: 80, getActions: (params) => [ ...

Checking if the Cursor is Currently Positioned on a Chart Element in Word Addin/OfficeJS

I am looking for a way to determine if the document cursor is currently positioned inside of a Chart element using the Microsoft Word API. My current application can successfully insert text, but when I attempt to insert text into the Chart title, it ends ...

retrieving information from a data attribute

When setting a data attribute for a user on a link, the code looks like this: <input type="button" class="btn" data-user={"user": "<%= @user.name %>"} value="Start" id="game"> Upon listening for the click event in the JavaScript function, co ...

Tips for aligning and emphasizing HTML content with audio stimuli

I am looking to add a unique feature where the text highlights as audio plays on a website. Similar to what we see on television, I would like the text to continue highlighting as the audio progresses. Could someone please provide me with guidance on how ...

Setting up TypeScript to use a connected component within a parent component: A step-by-step guide

I have created a connected component that utilizes mapStateToProps and mapDispatchToProps to inject the properties into the Props without the need for the parent to inject anything. However, TypeScript raises an error when I import it into another componen ...

How can I update getServerSideProps using a change event in Next.js?

Currently, I am faced with the task of updating product data based on different categories. In order to achieve this, I have set up an index page along with two components called Products and Categories. Initially, I retrieve all products using the getServ ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

Unusual symbols in angular variable found within an HTML document

Currently in my HTML, I have code like this: <li ng-repeat="favorite in favorites track by $index"> <a ng-href="javascript:void(0)" ng-click="changeSVG(favorite)"> <i class="fa fa-sitemap"></i>{{favorite}} </a> </l ...