What measures can be taken to stop both of these cubes from being dragged simultaneously?

Check out this drag example: https://codepen.io/alexcheninfo/pen/vKkgkE. You'll notice that if you stack cubes and drag the one in front, the one behind it moves as well.

Take a look at the complete code below:

<script>
  AFRAME.registerComponent('draggable', {
    init() {
      this.mouse = new THREE.Vector2();
      this.scene = this.el.sceneEl;
      this.camera = this.scene.camera;
      this.obj = this.el.object3D;

      this.scene.addEventListener('mousemove', e => {
        this.mouse.x = (e.offsetX / this.scene.canvas.offsetWidth) * 2 - 1;
        this.mouse.y = -(e.offsetY / this.scene.canvas.offsetHeight) * 2 + 1;

        if (this.selected) {
          let r = new THREE.Raycaster();
          r.setFromCamera(this.mouse, this.camera);
          let dist = this.obj.position.distanceTo(this.camera.position);
          let point = r.ray.direction.multiplyScalar(dist);
          this.el.setAttribute('position', `${point.x} ${point.y} ${point.z}`);
        }
      });

      this.scene.addEventListener('mousedown', e => {
        let r = new THREE.Raycaster();
        r.setFromCamera(this.mouse, this.camera);
        let intersected = r.intersectObject(this.el.object3D, true);
        let objPos = this.el.object3D.position;
        let camPos = this.camera.position;
        console.log(objPos.distanceTo(camPos));
        if (intersected.length) this.selected = true;
      });

      this.scene.addEventListener('mouseup', e => {
        this.selected = undefined;
      });
    }
  });
</script>

<a-scene>
  <a-entity camera look-controls></a-entity>
  <a-sky src="https://raw.githubusercontent.com/aframevr/aframe/master/examples/boilerplate/panorama/puydesancy.jpg"></a-sky>
  <a-box color="tomato" position="-3 0 -10" draggable></a-box>
  <a-box draggable position="3 0 -5" draggable></a-box>
</a-scene>

Any suggestions on how to prevent the cubes from moving together? For example, restricting movement to only the cube in the front?

Answer №1

The reason behind this issue lies in the placement of the control. Instead of having multiple raycasters for one camera, it is more efficient to have one raycaster that can detect all intersecting objects and return them sorted by distance. You can find more information about this concept at

Here's how I would restructure it:

  • Utilize the built-in raycaster component, which has an improved API on the upcoming 0.3.0 release. More details can be found at
  • Create a dragger component that relies on the raycaster component.
  • Ensure that the dragger component only intersects objects with the draggable component, class, or attribute.


    <a-scene>
      <a-camera>
        <a-entity dragger></a-entity>
      </a-camera>
      <a-entity draggable></a-entity>
    </a-scene>

AFRAME.registerComponent('dragger', {
  init: function () {
    // Configure raycaster.
    this.el.setAttribute('raycaster', {
      objects: '[draggable]',
      // ...
    });
  },

  tick: function () {
    // Access this.el.components.raycaster.intersectedEls
  }
});

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

The Mongoose connection keeps failing to reconnect and maintain a stable heartbeat

I am facing an issue with the automatic reconnection feature in mongoose on my project. Despite configuring it to reconnect after a certain interval, it does not work as expected. Even if the credentials are correct, mongoose should attempt to log in perio ...

Tips for optimizing content loading without a full page refresh using Ajax

As a newcomer to the world of coding, I am currently working as a beginner webdev specialist. My boss has tasked me with enhancing the website in a way that only the inner content is reloaded when the page is refreshed while keeping the top panel, side bar ...

There is only a single value visible from a concealed input

<?php foreach($_color_swatch as $_inner_option_id){ preg_match_all('/((#?[A-Za-z0-9]+))/', $_option_vals[$_inner_option_id]['internal_label'], $matches); if ( count($matches[0]) > 0 ) { $color_value = $matches[1][count($ma ...

Tips for transforming C#.NET code into JavaScript code

A few years back (around 3 or 4 years ago), I recall hearing about a fascinating concept that involved generating client-side JavaScript code from C#.NET source code. It may have been related to validation tasks specifically... Does anyone have more inform ...

Utilizing external functions within AngularJS Controller

I need to execute an external JS function that fetches data from a REST endpoint, which takes some time. The problem is that the graph is loading before the data is retrieved and inserted into it. External JS: function callEndpoint() { var sensorID = ...

Ways to showcase a JSON menu with a single level

I have a json file containing links to all the images in a specific folder, as shown below: ["http://img1.png","http://img2.png","http://img3.png","http://img4.png"] I would like to create a <ul> list using this data, but I'm not sure how to d ...

"Enhancing User Experience: Creating interactive interfaces with JQuery drag and drop

Live Example: http://jsfiddle.net/PWh2L/78/ $( ".droppable,.droppable1" ).sortable({ connectWith: '.droppable,.droppable1', revert: 200, tolerance:'pointer', start: function(){ }, stop: function(event,ui){ ...

How do I add a new item to an object using Ionic 2?

example item: this.advData = { 'title': this.addAdvS2.value.title , 'breadcrumb': this.suggestData.breadcrumb, 'price': this.addAdvS2.value.price ...

Material UI DateTimePicker Displaying Incorrectly

I am implementing a new Material UI date time picker on page load by setting the open prop. <Grid item xs={6} className={styles.CampaignDates_calendar_right}> <MuiPickersUtilsProvider utils={DateFnsUtils} className={styles.CampaignDates_calendar ...

The error message "POST .../wp-admin/admin-ajax.php net::ERR_CONNECTION_CLOSED" appears when a WordPress AJAX request receives data that exceeds 1MB in size

When I attempt to submit a jquery ajax form from the frontend and upload a blob (a variable of string) as a .txt file to WordPress using wp_handle_upload(), everything works smoothly until the file size reaches around 1mb. At that point, an error is displa ...

The URL for this page is not within the app's designated domains and will not open Facebook Dialogs (FB UI)

I am currently working on integrating Facebook UI Dialogs into my website. My goal is to add custom actions when users share a post from my site. I have created my app, added the app URL and domain (which is the same as the URL), and included all necessa ...

Obtain element by selecting a specific class using Javascript

<select class="tmcp-field tillagg-width tm-epo-field tmcp-select" name="tmcp_select_30" data-price="" data-rules="" data-original-rules="" id="tmcp_select_ ...

Discovering the state of a checkbox element in Java and Selenium can be a challenge, especially when the element is not identified as a checkbox even with the

I'm currently creating test scenarios for the aviasales.com website and I am attempting to confirm the status of a checkbox. Locating and clicking on the checkbox was simple using the following code: WebElement checkboxValue = driver.findElement(By ...

Struggling to successfully compile and release my Typescript library with webpack or TSC

I've developed a library that uses rx streams to track the state of an object, and now I'm looking to share it with the npm community. You can find the code on my Github repository. My goal is to compile the library into a single Javascript fil ...

How can I determine the transfer speed of a file being uploaded via jquery/Ajax?

As I upload a file using ajax/jquery, you can check out the demonstration here. The function provided will give you the percentage completion status: //progress bar function function OnProgress(event, position, total, percentComplete) { //Progress bar ...

Having trouble fetching AJAX POST data in PHP?

Attempting to send a variable as an object to my PHP file, but it's not receiving any data. Testing with window.alert(u.un) in the AJAX call shows that data is being passed successfully without errors in the console. However, the PHP file still does n ...

extract data from JSON using JavaScript

I am attempting to load a php/json file which contains the following data: echo '{'; echo '"position":['; while($inhoud = mysql_fetch_array($result)) { echo '{'; echo '"lat":"'.$inhoud['lat'].'",& ...

The function "getElementsByClassName" in Javascript is malfunctioning

I have redesigned my website by implementing an interactive feature where users can click on a tree image to remove it and replace it with a number using JavaScript. Initially, I targeted the specific tree with the following code: document.getElementById( ...

"Duplicate content issue with ng-transclude causing element to render twice

Why is the transcluded directive displaying Name inside directive = Frank twice? I believed I had a good grasp on transclusion, but this specific scenario has left me puzzled. Check out this fiddle for more details <div ng-app="myApp" ng-controller=" ...

During the Jasmine test, an error was encountered when trying to call a factory function that includes both a local and another function. The error message displayed

I have a factory with two functions and two local methods. I have written a Jasmine test case in which I expect the local method updateDetails and the factory function SavePref.savePref to be called when SavePref.saveDetails(values, prop); is invoked, as s ...