Determine the Normalized Mouse Motion Direction Across a Collection Using Three.js

JS Fiddle: http://jsfiddle.net/Nfw9M/1/

I am currently delving into the world of matrix operations and need assistance with a particular problem related to mouse movement on a 3D object. Inside my THREE.Object3D, there are three cube meshes that can be rotated in various directions. My goal is to determine the normalized vector direction of the mouse movement as it clicks and drags across the object.

To visualize the issue, imagine a scenario where the object is rotated 90 degrees on the X axis. If a user were to drag from left to right across the face of the black cube, the result would differ from dragging on an unrotated object's face.

Based on my research, I believe the steps I need to follow are:

  • Obtain the inverse matrix of the object group
  • Calculate the difference between vectors of two mouse movements
  • Multiply these vectors by the original inverse matrix
  • Normalize the result

However, I have hit a roadblock in my progress. I have intersection code that seems to work correctly, but I am unsure about the values returned by object.point.

On mouse movement, my current code snippet looks like this:

function mouseMove(e) {
    var hit = intersect(e);
    console.log(hit);
    if (!hit[0]) return false;
    var point = hit[0].point;

    if (_last) {
        var p = new THREE.Vector3();
        p.add(point);
        p.sub(_last);

        //I'm stuck at this point
    }

    _last = point;
}

This leads me to ponder whether it is viable to multiply a Vector3 and a Matrix4 together?

The task at hand appears quite intricate, and there are some gaps in my understanding hindering my progression. Any suggestions or guidance would be greatly appreciated!

Thank you for your help!

Answer №1

Success! I believe I've cracked the code!

Check out my JS Fiddle: http://jsfiddle.net/Nfw9M/2/

The key missing element was unprojectVector in the intersect function.

function intersect(e) {
    _vector.set((e.pageX / window.innerWidth) * 2 - 1, -(e.pageY / window.innerHeight) * 2 + 1, 0.5);
    _projector.unprojectVector(_vector, _camera);
    _ray.set(_camera.position, _vector.sub(_camera.position).normalize());
    return _ray.intersectObjects(_cube.children);
}

Here are the necessary steps:

  • Obtain the inverse of the object matrix
  • Convert the Vector3 intersect to Vector4
  • Multiply the Vector4 intersect values by the inverse of the object matrix
  • During mouse movement, subtract the Vector4 from the one set at mousedown.

    _inverse.getInverse(_cube.matrix);
    _v4.set(point.x, point.y, point.z, 1);
    _v4.applyMatrix4(_inverse);
    
    var v4 = new THREE.Vector4(_last.x, _last.y, _last.z, 1); //could avoid new here
    v4.sub(_v4);
    

Observing the changes in v4 over time will indicate the direction in x, y, or z space that the mouse is moving across the object as if it were not rotated at all.

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

NPM Messer - the innovative chat tool for Facebook Messenger. Ready to see it in action?

Previously, I had the idea of creating my own Messenger client. However, when I reviewed the documentation, it only provided instructions on how to write a chatbot. Despite this obstacle, I stumbled upon something intriguing - a Messer command line client. ...

Designing an opening interface for an HTML5 Canvas gaming experience?

It's common knowledge that the HTML5 Canvas element interfaces seamlessly with the incredibly efficient Javascript Engines found in Firefox, Safari and Chrome. Lately, I've been delving into game development using Javascript and the Canvas, and ...

Troubleshooting Django Templateview: Incorporating Bootstrap Popovers into HTML tables not functioning properly

https://i.stack.imgur.com/LXHJF.pngWhen loading this template, the HTML renders correctly and the table loads successfully. However, certain cells have special pop-over attributes that do not work after the HTML is loaded via an AJAX request on the same pa ...

Manipulating Object origin data

I'm unsure if this can be achieved. I am aiming to create a header and footer that remain the same while only switching the content pages. The resources I have at my disposal cover HTML, JS, CSS, and JQuery. Below is a simplified version of my curre ...

Ways to troubleshoot NPM installation issues related to gyp ERR

I have tried most of the suggestions found online, but I am still encountering an error when trying to install opencv and serialport. My current setup includes Visual Studio 2019 with C++ Desktop environment and Python 3.7. npm ERR! command C:\Windows ...

How to trigger a force reload on a VueJS route with a different query parameter?

Is there a method to refresh the page component when two pages utilize the same Component? I have encountered an issue where the router does not reload and the previous edit values persist. { path: "/products/new", component: ProductPage, meta: { ...

Utilize AngularJS to load pages through a single state

Is there a way to develop a method that can dynamically load the controller and template for each page as needed, upon changing routes? I am looking to enhance the state url option by including 2 parameters, with the second one being optional. This would a ...

Create a stylish div slider with interactive menu using Jquery

Currently, I am in need of creating a slider for a <div>. However, most plugins are too large for my needs, so I am attempting to develop my own jQuery script since I only require the basic functionality. Admittedly, I am a novice in jQuery and could ...

Dynamic loading of tinymce in progress

When tinymce is loaded in the head and before dom, everything works fine. However, if I attempt to load the JavaScript with ajax using jquery.getScript(), it doesn't work. I initialize tinymce when the user clicks the content area, so the dom must be ...

Is there a way to retrieve the day of the week based on the date provided by the user

function retrieveWeekday() { var input = document.getElementById("input"); } <form> <input type="date" placeholder="dd:mm:yy" id="input"/> <input type="button" value="get weekday" onclick="retrieveWeekday()"/> ...

Angular appears to be having trouble with localStorage functionality

Having an issue with my service that interacts with a local NOTES object array using localStorage. Whenever the page refreshes, the previously entered data is lost and only the initial data in the const NOTES array remains. Can't seem to figure out wh ...

Troubleshooting a glitch in AngularJS involving the interaction of multiple controllers and Gr

Struggling to make multiple controllers work with Grunt. It's not just a Grunt issue - even combining the files manually doesn't solve the problem. My goal is to use Grunt to build the application, with one controller per file to gradually expand ...

Optimizing Animation Effects: Tips for Improving jQuery and CSS Transitions Performance

Wouldn't it be cool to have a magic line that follows your mouse as you navigate through the header menu? Take a look at this example: It works seamlessly and smoothly. I tried implementing a similar jQuery script myself, but it's not as smoot ...

Superbase Email Forwarding

Is it possible to create a dynamic redirect link in the confirmation email that directs users to a specific page after creating an account? For instance: If a user visits the website using a link such as www.website.com/project/1 or /project/2 etc. and t ...

Upon the initial hover, the data added to the title tag following an Ajax call is not appearing

I am currently working on an ajax request that retrieves information such as username, email, and user_id. Once the ajax call is successful, I use jQuery to append this data to the title tag. The main issue I am facing is that the data is only displayed af ...

Unconventional way of assigning class properties in Typescript (Javascript): '?='

Recently, I came across the ?= assignment expression within a class property declaration. Can anyone provide some insight into what this means? I am familiar with the new Optional Chaining feature (object?.prop), but this particular syntax is unfamiliar t ...

Generating symbols that combine both images and text seamlessly

I am working with a circle image that I need to resize based on its placement. This image is intended to be a background for a character or two of text. Specifically, whenever the number 1 or 2 appears in a certain element, I want the circle to appear beh ...

Trigger a jQuery modal by clicking on a cell within a table

As a novice in jquery, I am facing a challenge. I have a table with a column showing the total number of employees in a department. When a user clicks on this column, it should open up a jquery modal displaying a list of employees like EmpA, EmpB, and Em ...

Attaching an input text box to an Angular $scope is not possible

In my angular app, I have a piece of markup that showcases a table with saved queries. Each query has the option to add a title using an input field. When you click the edit icon, it should display the newly created title. <table class="table table-str ...

Problem with Bootstrap-slider not loading correctly

I seem to be facing an issue with selecting DOM elements that are part of bootstrap-slider. When I try to target them with events like click, nothing happens. All events work fine when the page is refreshed. What could be causing this problem? $(document ...