Step by step guide on moving a scene in Three.js

Is there a way to drag the scene when moving the mouse left or right without rotating the camera?

I attempted


camera.position.x = mouseX;  
camera.position.y = mouseY;  

However, this resulted in the scene rotating.

Even changing the position in the scene caused rotation.

Any suggestions on how to successfully drag the scene?

Answer №1

If you want to enhance your camera control, you can try the following steps after defining your camera:

controls = new THREE.RollControls(camera);
controls.movementSpeed = 10;
controls.lookSpeed = 1;
controls.rollSpeed = 0;
controls.autoForward = false;

Make sure to include this in your HTML file as well:

<script type="text/javascript" src="custom-folder/three-js/RollControls.js"></script>

Moreover, remember to update your onWindowResize event with

controls.handleResize();

Adjust your render() function by adding

controls.update(clock.getDelta());

Finally, modify your init() function by incorporating

clock = new THREE.Clock();

Answer №2

Found this helpful file on GitHub that could be useful for your project.

 THREE.DragControls = function(_camera, _objects, _domElement) {

 if (_objects instanceof THREE.Scene) {

_objects = _objects.children;

 }

 var _projector = new THREE.Projector();

 var _mouse = new THREE.Vector3(),

    _offset = new THREE.Vector3();

var _selected;

_domElement.addEventListener('mousemove', onDocumentMouseMove, false);

_domElement.addEventListener('mousedown', onDocumentMouseDown, false);

_domElement.addEventListener('mouseup', onDocumentMouseUp, false);


function onDocumentMouseMove(event) {

  event.preventDefault();

   _mouse.x = (event.clientX / _domElement.width) * 2 - 1;

   _mouse.y = -(event.clientY / _domElement.height) * 2 + 1;

    var ray = _projector.pickingRay(_mouse, _camera);

    if (_selected) {

         var targetPos = ray.direction.clone().multiplyScalar(_selected.distance).addSelf(ray.origin);

         _selected.object.position.copy(targetPos.subSelf(_offset));

        return;

   }


    var intersects = ray.intersectObjects(_objects);

    if (intersects.length > 0) {

       _domElement.style.cursor = 'pointer';

    } else {

        _domElement.style.cursor = 'auto';

    }

  }

   function onDocumentMouseDown(event) {

     event.preventDefault();

     _mouse.x = (event.clientX / _domElement.width) * 2 - 1;

     _mouse.y = -(event.clientY / _domElement.height) * 2 + 1;

     var ray = _projector.pickingRay(_mouse, _camera);

     var intersects = ray.intersectObjects(_objects);

     if (intersects.length > 0) {

         _selected = intersects[0];

         _offset.copy(_selected.point).subSelf(_selected.object.position);

         _domElement.style.cursor = 'move';
   }        
  }


  function onDocumentMouseUp(event) {

     event.preventDefault();

     if (_selected) {

         _selected = null;

    }

     _domElement.style.cursor = 'auto';

 }

  }

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

Leveraging webpack2 for code splitting with the CommonsChunkPlugin

I encountered an issue while using code splitting and the CommonsChunkPlugin. My previous experience with require.js involved files being automatically cached. Additionally, I have configured my webpack with libraryTarget: 'amd'. When looking at ...

Find the difference between the sum of diagonals in a 2D matrix using JavaScript

I'm currently practicing on hackerrank and came across a challenge involving a two-dimensional matrix. Unfortunately, I encountered an error in my code implementation. 11 2 4 4 5 6 10 8 -12 The task at hand is to calculate the sum along the primary ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

The `$refs` variable in Vue can be used to reference a specific Vue component within a class-st

Would it be possible to access this.$refs.label? I am using the package vue-property-decorator. Below is the content of the component: <template> <div> <label ref="label">asd</label> </div> </template> <scr ...

Create an HTML and CSS code that allows you to split paragraph text into columns within a

I am seeking a way to create dynamic paragraph column text using only the https://i.sstatic.net/ZX1AN.png Here is an example of how it could be displayed in HTML: <div> <p> Sed ut perspiciatis, unde omnis iste natus error sit voluptatem ...

QuickFit, the jQuery plugin, automatically adjusts the size of text that is too large

I have incorporated the QuickFit library into my website to automatically resize text. However, I am running into an issue where the text is exceeding the boundaries of its containing div with a fixed size. This is something I need to rectify. This is ho ...

Synchronize Protractor with an Angular application embedded within an iframe on a non-Angular web platform

I'm having trouble accessing elements using methods like by.binding(). The project structure looks like this: There is a non-angular website | --> Inside an iframe | --> There is an angular app Here's a part of the code I'm ...

What steps can be taken in Javascript to handle a response status code of 500?

I am currently utilizing a login form to generate and send a URL (referred to as the "full url" stored in the script below) that is expected to return a JSON object. If the login details are accurate, the backend will respond with a JSON object containing ...

Tips for creating a responsive Livewire Pagination system

Looking to make Livewire pagination responsive? When using Bootstrap, simply add flex-wrap to the pagination class to ensure responsiveness. Component: class Index extends Component { use WithPagination; protected $paginationTheme = 'bootstr ...

jQuery Counter Effect encountering isNaN error when trying to display a number retrieved from a get API object

I am looking to display the numerical data retrieved from an API using JSON. I want to incorporate a counter effect that displays "isNaN" if necessary. The API URL returns an object with the total number saved in data.data. Can anyone assist me with achi ...

Designing CSS elements that flow from top to bottom, left to right, and extend to the right when overflowing

I'm attempting to create a layout where divs are displayed from top to bottom, but once they reach the bottom of the browser window, any additional divs will overflow to the right. You can take a look at the desired layout here: https://i.stack.imgur. ...

Duplicate the identical data retrieval query, this time utilizing a JavaScript Ajax post method

To enhance the data request query, implement a JavaScript Ajax post method to avoid page refresh when the button is pressed. This will allow for requesting another page and displaying it in a designated section on the webpage. Here's the code snippet ...

Using Gmail with Nodemailer is throwing an error: "Cannot add property 'mailer' on a string with value 'SMTP'."

I am facing an issue with sending data from a form to my Gmail account. Whenever I click the submit button, I encounter the same error message repeatedly. Despite researching various problems related to nodemailer, none of them match the specific problem t ...

Testing inherit from a parent class in a unit test for Angular 2

Trying to create a unit test that checks if the method from the base class is being called This is the base class: export abstract class Animal{ protected eatFood() { console.log("EAT FOOD!") } } Here is the class under test: export ...

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

Issue with JavaScript ScrollTop

Simply put, I am trying to determine the total scroll size for a text area in a unit that scrollTop can align with. However, I am at a loss on how to do so. I've tried scrollHeight and various other methods without success. Any advice or suggestions ...

Adding a Data Attribute to Bootstrap 5 Popovers

I'm facing an issue with a group of buttons that have a data-attribute I want to include in the popover they trigger. HTML: <button type="button" class="btn btn-yellow btn-deleteTeacher" data-bs-toggle="popover" role= ...

What is the best way to rearrange DOM elements using the output of a shuffle function?

Looking for a solution to shuffle and move around cards in an HTML memory game? Let's analyze the current setup: <ul class="deck"> <li class="card"> <i class="fa fa-diamond"></i> </li> ...

Is it possible to globally delay the execution of WebElement.sendKeys() in Protractor's onPrepare function?

While running protractor on a sluggish machine, I am in need of slowing down each key press and action performed. The action part has been successfully implemented, but how can I achieve the same for key presses? I have come up with a local solution which ...

Tips for transferring a Spring MVC controller variable to JavaScript

I am currently working on retrieving a variable for a JavaScript function from an object that is sent to the view by the controller. The object I am dealing with is called Bpmsn. https://i.sstatic.net/FxlAo.png Through the controller, I have injected th ...