Circling the central point by utilizing the device's positioning

I have been attempting to recreate the functionality of Google's Cardboard Demo "Exhibit" using three.js. I started with the example provided on the Chrome Experiments website and added code to draw a simple triangular pyramid in the init method:

function init() {
  renderer = new THREE.WebGLRenderer();
  element = renderer.domElement;
  container = document.getElementById('example');
  container.appendChild(element);

  effect = new THREE.StereoEffect(renderer);

  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera(90, 1, 0.001, 700);
  camera.position.set(0, 0, 50);
  scene.add(camera);

  controls = new THREE.OrbitControls(camera, element);
  controls.rotateUp(Math.PI / 4);
  controls.noZoom = true;
  controls.noPan = true;

  var geometry = new THREE.CylinderGeometry( 0, 10, 30, 4, 1 );
  var material = new THREE.MeshPhongMaterial( { color:0xffffff, shading: THREE.FlatShading } );

  var mesh = new THREE.Mesh( geometry, material );
  mesh.updateMatrix();
  mesh.matrixAutoUpdate = false;
  scene.add( mesh );

  var light = new THREE.DirectionalLight( 0xffffff );
  light.position.set( 1, 1, 1 );
  scene.add( light );

  light = new THREE.DirectionalLight( 0x002288 );
  light.position.set( -1, -1, -1 );
  scene.add( light );

  light = new THREE.AmbientLight( 0x222222 );
  scene.add( light );

  function setOrientationControls(e) {
    if (!e.alpha) {
      return;
    }

    controls = new THREE.DeviceOrientationControls(camera);
    controls.connect();
    controls.update();

    element.addEventListener('click', fullscreen, false);

    window.removeEventListener('deviceorientation', setOrientationControls, true);
  }
  window.addEventListener('deviceorientation', setOrientationControls, true);

  window.addEventListener('resize', resize, false);
  setTimeout(resize, 1);
}

The OrbitControls method functions perfectly on desktop: the screen orbits around the pyramid when dragged with the mouse. However, on mobile using DeviceOrientationControls, this effect is lost and the camera moves freely at (0, 0, 0). I followed the suggestion from a previous question and replaced camera with scene like so:

controls = new THREE.DeviceOrientationControls(scene);

Unfortunately, this did not work and nothing moved when the device was rotated. What adjustments should I make to achieve the OrbitControls behavior using DeviceOrientationControls motion?

Answer №1

If you want to create a deviceorientation orbit controler similar to the one showcased in this demo, you'll need to make modifications to the existing OrbitControls.js.

You can view the changes made to the file in this commit on github: https://github.com/snovak/three.js/commit/f6542ab3d95b1c746ab4d39ab5d3253720830dd3

I've been planning to submit a pull request for quite some time now, but I haven't had the chance to do so yet. There are still some clean-up tasks that need to be done.

You can download my customized OrbitControls.js here (please note that I haven't merged it in months, so results may vary): https://raw.githubusercontent.com/snovak/three.js/master/examples/js/controls/OrbitControls.js

Below is the implementation of the modified OrbitControls in your scripts:

this.controls = new THREE.OrbitControls( camera, document.getElementById('screen') ) ;

            controls.tiltEnabled = true ;  // default is false.  You need to turn this on to control with the gyro sensor.

            controls.minPolarAngle = Math.PI * 0.4; // radians
            controls.maxPolarAngle = Math.PI * 0.6; // radians
            controls.noZoom = true ;

            // How far you can rotate on the horizontal axis, upper and lower limits.
            // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
            controls.minAzimuthAngle = - Math.PI * 0.1; // radians
            controls.maxAzimuthAngle = Math.PI * 0.1; // radians

            this.UMLogo = scene.children[1];
            controls.target = UMLogo.position;

I trust this information will help you achieve your desired outcome! :-)

Answer №2

In order to properly utilize the DeviceOrientationControls, it is crucial to include the controls.update() function within your animation loop. Failing to do so will result in the control not accurately adjusting its position according to device data.

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

Commitment within a forEach iteration

While working with a foreach loop, I am facing some challenges. Here is the scenario: I have multiple elements stored in an object array. For each object, I need to execute two queries. After completing the queries for one object, I move on to the next and ...

The radio button in the HTML form is disabled when the user selects

I have two radio buttons labeled Billable "Y" and Billable "N". These radio buttons are linked to a database with corresponding values of "Y" or "N". If the user selects "Y" using the radio button, then the NonBillableReason text box should be disabled. ...

Utilizing FullCalendar for showcasing comprehensive details

I'm a big fan of the fullcalendar plugin and all its amazing features. I want to enhance it by displaying more customized information for each event when in agendaWeek or agendaMonth view. Switching between views is easy, but I need help filtering out ...

Encountering a loading error with r.js while attempting to optimize

In my main.js file, I have the following configuration for Require.js: /*--- Setting up Require.js as the main module loader ---*/ require.config({ baseUrl: '/javascripts/libs/home/', waitSeconds: 0, paths : { jquer ...

Preventing click event from bubbling up the DOM: Using Vue's @click

How can I access the child elements within a parent component? <div v-on:click.stop.prevent="onClickTemplateHandler"> <div> <h3 style="">Title</h3> <p>{{ lorem }}</p> </div> ...

Standardize API data for utilization in Redux

I have an API that provides the following data: const data = { id: 1, name: 'myboard', columns: [ { id: 1, name: 'col1', cards: [ { id: 1, name: 'card1' }, { id: 2, name: 'card ...

Javascript code for scrolling to the top isn't functioning as expected

I found a helpful code snippet for adding a scroll to top button on my webpage at the following link: http://jsfiddle.net/neeklamy/RpPEe/ Although I implemented the code provided, unfortunately, the scroll to top button is not displaying correctly. Here ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

Tips for successfully incorporating a jQuery plugin into your React project

I'm attempting to incorporate the Air Datepicker library by t1m0n into my React application, but I'm encountering difficulties. import React from 'react'; import AirDatepicker from 'air-datepicker'; class Datepicker extend ...

Why is it that the condition of being undefined or not functioning properly in state?

I am currently facing an issue with a piece of code I wrote in React JS. The state variable is not functioning as expected and even after modifying it upon button click, nothing seems to be working. After checking the console, I noticed that the state rema ...

Display a div when hovering over another div

I have a menu that looks like this: https://i.sstatic.net/WqN33.png and I want to create a hover effect where another div shows up over each item, similar to this: https://i.sstatic.net/JRaoF.png However, I can't seem to figure out how to implemen ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

JQuery isn't functioning properly on dynamically generated divs from JavaScript

I'm currently tackling an assignment as part of my learning journey with The Odin Project. You can check it out here: Despite creating the divs using JavaScript or jQuery as specified in the project requirements, I am unable to get jQuery's .hov ...

modify the final attribute's value

Hello I've been using skrollr js to create a parallax website. However, the issue arises when determining the section height, as it depends on the content within. My goal is to locate the last attribute and adjust the number value based on the section ...

Making a dropdown menu spin using Jquery and Javascript

I am in need of a unique solution for a dropdown menu that appears rotated 90 degrees anticlockwise. The goal is to have the dropdown select "button" text displayed vertically, with the options sliding out in a similarly rotated, sideways manner featuring ...

Is there a way to execute a tanstack react query externally, as I am unable to utilize useQuery within the component?

const fetchSurveyData = useQuery(["survey"], () => getSurveyData({ page: 1, userLangCode: langCode, sortColumnName: "Date", sortColumnOrder: "DESC", country, ip, }) ); After tr ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...

Error message "Error: listen EADDRINUSE" is reported by node.js when calling child_process.fork

Whenever the 'child_process.fork('./driver')' command is executed, an error occurs: Error: listen EADDRINUSE at exports._errnoException (util.js:746:11) at Agent.Server._listen2 (net.js:1156:14) at listen (net.js:1182:10) ...

Utilizing the request body value within the .withMessage() function of the Express validator chain

I am looking to showcase my express validator errors with the specific value entered by the user. For instance, if a user types in an invalid username like "$@#" (using a regex that I will provide), I want to return my error message as follows : { "er ...

Adding an object to an array of objects with the useState hook in React - A simple guide

Hello, I am currently working on a project that involves creating a dynamic test page with questions, answers, and points/grades. The goal is to generate input fields based on the number of questions selected by the admin, along with an "Add Question" butt ...