How can I make a Three.js Physijs mesh move towards the mouse?

After browsing through various posts and documentation, I am trying to figure out how to make a BoxMesh follow the mouse cursor. My ultimate goal is to implement joystick touch controls for games like Heroes of Loot. For now, I am focusing on getting directional velocity to work correctly.

Here's what I have in my mouse down event:

if (scene.mouseControls.isDown) {
  var coords = scene.mouseControls.screenCoords;
  var vector = new THREE.Vector3();

  vector.set(
    ( scene.mouseControls.screenCoords.x / window.innerWidth ) * 2 - 1,
    0.5,
    - ( scene.mouseControls.screenCoords.y / window.innerHeight ) * 2 + 1
  );
  vector.unproject(scene.camera);

  var p1 = this.mesh.position;
  var p2 = vector;
  var angle = Math.atan2(p2.x - p1.x, p2.z - p1.z);
  var velX = Math.sin(angle) * 20;
  var velZ = Math.cos(angle) * 20;

  console.log(vector.x, vector.z);

  this.mesh.setLinearVelocity(new THREE.Vector3(velX, 0, velZ));
}
else {
  this.mesh.setLinearVelocity(notMovingVector);
}

However, the calculated velocity seems to oscillate back and forth, resulting in jittery player movement.

This is how I set the mouse coordinates:

window.addEventListener(activeEventList[POINTER_MOVE], function (e) {
  if (e.touches) {
    var t = e.touches[0];
    _this.screenCoords.x = t.clientX;
    _this.screenCoords.y = t.clientY;
  }
  else {
    _this.screenCoords.x = e.clientX;
    _this.screenCoords.y = e.clientY;
  }
});

I am not considering scroll offset since the scene covers the entire screen.

Edit

I have removed the previous direction code and instead used atan2 to calculate an angle and apply it, similar to how I've done it in 2D games.

Answer №1

After some thought and experimentation, I was able to solve the problem at hand. While my initial attempt using atan2 was on the right track, it required reintroducing multiplyScalar for success. The issue stemmed from utilizing the camera's X & Y values to determine distance, resulting in a discrepancy between visual perception and the plane's actual dimensions.

Here is the revised approach I took:

if (scene.mouseControls.isDown) {
  var coords = scene.mouseControls.screenCoords;
  var vector = new THREE.Vector3();

  vector.set(
    ( scene.mouseControls.screenCoords.x / window.innerWidth ) * 2 - 1,
    - ( scene.mouseControls.screenCoords.y / window.innerHeight ) * 2 + 1,
    0.5
  );
  vector.unproject(scene.camera);

  var dir = vector.sub(scene.camera.position).normalize();
  var distance = - scene.camera.position.y / dir.y;

  var p1 = this.mesh.position;
  var p2 = scene.camera.position.clone().add(dir.multiplyScalar(distance));

  var angle = Math.atan2(p2.z - p1.z, p2.x - p1.x);
  var velX = Math.cos(angle) * 20;
  var velZ = Math.sin(angle) * 20;

  this.mesh.setLinearVelocity(new THREE.Vector3(velX, 0, velZ));
}

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

Conceal the scroll bar while still allowing for scrolling functionality

In this code snippet, I am trying to maintain the scroll position of two blocks by syncing them together. Specifically, I want to hide the scrollbar of the left block while scrolling the right one. If anyone has any suggestions or solutions for achieving ...

In my PHP loop, I am creating radio buttons and I only want one of them to be selected at a time

How can I ensure that only one radio button is selected out of the 99 radio buttons generated in this for loop? for($x = 2; $x <= 101; $x++){ $out .= "<img src='/img/channel_icons/".$icons[$x]."' class='ch ...

Begin by adding the sub Route at the start of the route path in Angular

How can I dynamically add a user's name to all routing pages in my Angular project when they type the URL like www.mysite.com/hisName? The desired result should be www.mysite.com/hisName/home This is the routing code I have: import { NgModule } from ...

Guide on utilizing a map with both String and double values within the Struts 2 framework

I have a question about passing a HashMap with String and double values from an Action to JavaScript code. How can this be achieved? When editing fields with double values, I encounter null values on those fields. What is the best way to resolve this issu ...

Retrieve the earliest and latest dates from a JSON file to utilize with FlatPicker

I have a file in an unknown format, possibly JSON, with dates listed. I am attempting to extract the minimum and maximum dates from this data in MM/DD/YYYY format for use as variables in Flatpicker's minDate and maxDate options. The current AJAX call ...

What is the best way to hide the next/previous tabs once the jQuery dataTable has been set up using jSON data

Setting up a jQuery table using JSON data. Despite knowing that there will only be one row, the next/previous tabs are still displayed after the table. Is there a way to remove them? Here is the code for the table: table = $("#retrievedTable").dataTabl ...

The 'Required' attribute in HTML is malfunctioning

The 'required' attribute is not functioning properly when I try to submit the form. I've searched online for a solution, but none of them have resolved my problem. Take a look at the code snippet below - I've used the required attribute ...

Adjusting the transparency of the object's interior

I used the side property to give my object an interior, but it also reflects the exterior: let material = new THREE.MeshStandardMaterial({side: THREE.DoubleSide}); https://i.sstatic.net/oikad.png https://i.sstatic.net/Vb03K.png Is there a way to red ...

Error message "Undefined is not a function" occurred while using jQuery's .replace and scrollTop functions

I'm having issues with the scroll function in my code. It doesn't seem to be able to locate the ids in my HTML, even though I can't figure out why. I had a previous version that worked perfectly fine (unfortunately, I didn't save it D:) ...

I am having trouble with node.js express not recognizing the path to my CSS files

My objective is to load information onto an HTML page using Node.js and Express. The issue I am facing is that when I try to open the main page (which displays all the books from the database), everything works smoothly - the CSS and JS files are located ...

The InfoWindow on Google Maps is positioned above the Marker

My struggle lies in positioning the infowindow above my Google Maps API marker, as the infowindow keeps hiding the marker. I attempted using CSS to adjust the position of both elements, but unfortunately, it didn't have the desired effect. Here is th ...

Laravel validation successfully validates Vanilla AJAX request, but the controller does not receive the values

Currently, I am utilizing AJAX (vanilla JS) to send a form to a Laravel 5.5 controller for searching the Amazon products API. The AJAX is sending the correct keywords and category inputs, but the controller is not receiving them. Even though the request p ...

Unable to retrieve the complete count of invitations made by a user

My goal is to retrieve the invites of the author of a specific command within one server. I have experimented with various solutions, but many appear outdated or incorrect. Here is my current approach: exports.run = async (client, message, args) => { ...

building CharFields dynamically in Django

I am looking to gather input from the user using CharField. Using the value entered in CharField, I want to generate the same number of CharFields on the same page. For example, if the user enters "3" and clicks OK, it should display "3" CharFields below ...

Error encountered with Node.js clustering

Hey there! I'm currently diving into the world of node.js and javascript. My goal is to build a cluster.js using the nodejs cluster module, where at the end of my if statement I invoke server.js to kickstart the application. Here's my cluster.js ...

When attempting to create text with Three.js using the TextBufferGeometry method, an error arises indicating that the property yMax is unreadable due

While trying to add text to a three.js scene, I encountered the error message "Uncaught TypeError: Cannot read property 'yMax' of undefined". let loader = new THREE.FontLoader(); let font = loader.parse( jsonFont ); let geometry = new THRE ...

How to sequentially load multiple obj files in Three.js

Currently, I am utilizing the obj/mtl loader from three.js to import various obj files along with mtl files. The challenge I am facing now is the need to load multiple objs one by one. Even though I have implemented THREE.DefaultLoadingManager.onProgress t ...

Add an element to an array using the `push` method in JavaScript

I am currently studying the code for creating a canvas circle motion trail effect. I am a bit puzzled by the push(x:Pos,y:Pos) within thestoreLastPosition() function in the sample code provided below: ctx = canvas.getContext('2d'); var xPos = - ...

Is there a way to utilize a parameter for the user's input instead of relying on document.getElementById when incorporating a button?

let totalScore = 0; var myArray = [1, 2, 3, 4, 5]; let randomNum; function NumGuess(userInput) { var userGuess = userInput; var i; for (i = 0; i < 1; i++) { var randomNum = myArray[Math.floor(Math.random() * myArray.length)]; } if (us ...

Vue Testing Utilities - issue with data not updating upon click event activation

I recently created a basic test using Vue Test Utils: import { mount } from '@vue/test-utils' const App = { template: ` <p>Count: {{ count }}</p> <button @click="handleClick">Increment</button> `, ...