Rotation feature is not functioning on Three.js Trackball zoom, however zoom is working

As the title suggests, I am having trouble with trackerballcontrols. I am expecting it to work similar to this example, where I can rotate the camera but for some reason, I can only zoom in and out. Of course, I would like to be able to rotate the camera. Below is the code snippet I am using.

        <!DOCTYPE html>
        <html>
        <head>
        <title>Page Title</title>
        </head>
        <body>
        
        <h1>FooBarBaz</h1>
        <p>LaDeDa</p>
        <script src="http://threejs.org/build/three.min.js"></script>
        <script src="https://threejs.org/examples/js/controls/TrackballControls.js"></script>
        <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
        
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize( window.innerWidth, window.innerHeight );
        
        // Rest of the code remains the same...
 

Answer №1

There are a couple of adjustments needed in your code.

  1. Prior to initializing controls, ensure that you append renderer.domElement to the body:

    document.body.appendChild(renderer.domElement);

    var controls = new THREE.TrackballControls(camera, renderer.domElement);

  2. Given that you set your camera.position on the y-axis and TrackballControls defaults camera.up to the y-axis, your controls may not function correctly. To rectify this issue, modify the default camera.up behavior:

    camera.up = new THREE.Vector3(1, 1, 1);//feel free to adjust the values, just avoid making it parallel to the y-axis

    I'm not an expert in ThreeJS, for more details please refer to:https://github.com/mrdoob/three.js/issues/10161

The corrected code snippet is as follows:

<!DOCTYPE html>
<html>

<head>
<title>Page Title</title>
</head>

<body>
<h1>FooBarBaz</h1>
<p>LaDeDa</p>
<script src="http://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/TrackballControls.js"></script>
<script>
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);


    var objects = [
        {
            name: "earth",
            mesh: new THREE.Mesh(new THREE.SphereGeometry(1, 32, 32), new THREE.MeshPhongMaterial()),
            init: function (scene) {
                this.mesh.position.set(0, 0, 0);
                //this.material.map = THREE.ImageUtils.loadTexture('../earth.jpg');
                scene.add(this.mesh);
            },
            animate: function (t) { return }
        },
        {
            name: "satellite",
            mesh: new THREE.Mesh(new THREE.SphereGeometry(0.1, 32, 32), new THREE.MeshPhongMaterial()),
            init: function (scene) {
                this.mesh.position.set(1.5, 0, 0);
                //this.material.map = THREE.ImageUtils.loadTexture('../earth.jpg');
                scene.add(this.mesh);
            },
            animate: function (t) { this.mesh.position.set(Math.sin(t) * 1.5, Math.cos(t) * 1.5, 0); }
        }];
    objects.forEach(object => object.init(scene));

    var light = new THREE.HemisphereLight(0xf6e86d, 0x404040, 0.5);
    scene.add(light);

    camera.position.x = 0;
    camera.position.y = -5;
    camera.position.z = 0;
    camera.up = new THREE.Vector3(1, 1, 1);

    camera.lookAt(new THREE.Vector3(0, 0, 0));
    var timeStep = 0.01;
    var time = 0;

    document.body.appendChild(renderer.domElement);
    var controls = new THREE.TrackballControls(camera, renderer.domElement);
    controls.target.set(0, 0, 0);
    var render = function () {
        time += timeStep;
        requestAnimationFrame(render);
        objects.forEach(object => object.animate(time));
        controls.update();
        renderer.render(scene, camera);
    }

    render();</script>
</body>

</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

What is the best method for executing an application on the client side using Node.js?

Is it possible to initiate communication with an external program from the client side? Imagine I have a Node.js server paired with AngularJS or another framework. I want users to be able to click a button on the browser, causing a pre-installed client-si ...

Is it possible for the useUser() function within the Auth0 nextjs-auth0 library to retrieve user information without relying on cookie data?

The useUser() method by Auth0 is designed to retrieve information about a logged-in user by calling the /api/auth/me endpoint. This triggers the handleAuth() function, which sets up Auth0 (creating a sessionCache instance, etc.) and calls profileHandler(re ...

Failed: Protractor could not synchronize with the page due to an error saying "angular is not present on the window"

I encountered an issue with my Protractor test scripts where I started receiving an error message. Everything was working smoothly until I made some updates to a few scripts in my projects. The error occurs at the end of running the scripts. I attempted ...

Is there a reason why async functions do not function properly within a controller's get() handler?

Utilizing Node and Express along with the mssql npm package, I establish a connection to an SQL Server database in my app.js file by setting up a global variable that creates a connectionPool (I've excluded some boilerplate code for brevity): const m ...

Enhance your website's performance by optimizing Javascript page loading time when using

I've implemented a simple JavaScript function that calculates the loading time of a URL: var beforeLoad = (new Date()).getTime(); $('#myiframe').one('load', function() { var afterLoad = (new Date()).getTime(); var result = ...

What is the reason behind react-router-dom not supplying location.key during the initial page load?

In my component screen using react-router, I heavily rely on the parameter location.key to identify paths and other elements (using location.pathname did not resolve the issue). However, I noticed that when I first load my app, react-router does not have ...

Completing a form and reloading the page without including the reload in the browsing history

I am currently developing a compact web application using Flask, and I have encountered a challenging issue with navigating back to the previous page. Here are some approaches I have experimented with: Avoiding navigation away from the page - content ...

What is the best way to add a "Save to Favorites" link within a modal window

I have integrated the NASA API to showcase images, where clicking on an image reveals a modal containing additional details. There is also a save to favorites functionality in the tutorial that allows users to save images and details to a local storage sec ...

What is causing TypeScript to compile and remove local variables in my Angular base controller?

I am trying to develop a base controller in Typescript/Angular for accessing form data, but I'm encountering an issue where the form member seems to be getting removed during compilation and is not present in the generated JavaScript code. Could you ...

Click the button in Javascript to add new content

I am currently experimenting with JavaScript to dynamically add new content upon clicking a button. Although I have successfully implemented the JavaScript code to work when the button is clicked once, I would like it to produce a new 'hello world&ap ...

Techniques for sending PHP variables to window.location using JavaScript

How can I successfully include a PHP variable in a JavaScript window.location function? The current code snippet below does not seem to be working for me. echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.&apos ...

How can I maintain the default function for links that have been clicked using window.on('click') event listener?

I am currently working on a project to visualize the spatial positions of 4673 of the closest galaxies. To enhance the user experience, I have implemented customized click events that allow users to focus on individual galaxies and even change their colors ...

Tips on ensuring Angular calls you back once the view is ready

My issue arises when I update a dropdown list on one of my pages and need to trigger a refresh method on this dropdown upon updating the items. Unfortunately, I am unsure how to capture an event for this specific scenario. It seems like enlisting Angular ...

When clicking on the dropdown items of another button, the class of the child element in the Bootstrap button dropdown is being removed

Check out the JSFiddle for this code snippet. I'm attempting to implement Bootstrap's drop-down menu using list items instead of options. When a list item is selected, the data should be retrieved and displayed as an active selection within a bu ...

Maximizing the Efficiency of Three js with Image Textures for Faster Performance

I have some code to share, but unfortunately, I don't have the images to upload along with it. Within the code, there are two functions present: UseMeshNormalMaterial() and UsePngMaterial(). This setup allows you to easily test the code if you happ ...

BS4 Dynamic Countdown Clock

I have successfully integrated a countdown timer into my website, utilizing the following HTML code: <div id="clockdiv"> <div> <span class="days"></span> <div class="smalltext">Days</ ...

Utilizing class attributes within multiple classes

I have created a custom class called MutationValidator as follows: const ERR_MSG = 'Error1'; @Service() export class MutationValidator { .. } This class is used in another class like so: import { MutationValidator } from './mutation ...

Enable a button or class to dynamically alter its color

Hi there! I'm new to coding and just started learning HTML and CSS. My question is: How can I change the color of buttons once they are clicked? <div class="icon-bar"> <a href="#"><i class="fa fa-search" ...

Customize dropdown item colors in React using a color picker

I am currently utilizing a react color picker to create a personalized 16 color gradient. The process involves selecting a color from a dropdown menu and then using the color picker to make adjustments. This action updates an array that dictates the stylin ...

What are the benefits of integrating firebase-admin-sdk with firebase-ui and firebase-client-sdk for both server-side and client-side authentication management?

I am currently working on implementing an authentication mechanism for my Next.js project. Specifically, I plan to utilize firebase-auth and firestore. My main goal is to keep important security logic on the server side to ensure safety. I want to avoid ex ...