Position a BoxGeometry in a straight line between two points in 3D space

In my game, I have the ability for players to add objects to a world without being restricted to a grid. Now, I am working on adding footpaths to the game. When the player clicks on "Create footpath", they can add a point in the world at the location of the raycaster. Once the first point is placed, they can then add a second point to create a line/footpath visible from the first to the second point.

Creating a simple line using THREE.Line is straightforward. Here's the code snippet:

var lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push( new THREE.Vector3(x1,0,z1), new THREE.Vector3(x2,0,z2) );
lineGeometry.computeLineDistances();
var lineMaterial = new THREE.LineBasicMaterial( { color: 0xFF0000 } );
var line = new THREE.Line( lineGeometry, lineMaterial );
scene.add(line);

Now, I want to achieve something similar with a Mesh object but add a texture to it. I have the positions of the first and second points, as well as the length between them for the footpath. However, I'm unsure how to calculate the necessary rotation.

I've heard about LookAt, could this be a solution? How can I implement this with a mesh?

Any help on determining the correct rotation for the footpath object would be greatly appreciated.

Here is the code snippet I use for creating the footpath mesh:

var loader = new THREE.TextureLoader();
loader.load('images/floor.jpg', function ( texture ) {
    var geometry = new THREE.BoxGeometry(10, 0, 2);
    var material = new THREE.MeshBasicMaterial({ map: texture, overdraw: 0.5 });
    var footpath = new THREE.Mesh(geometry, material);
    footpath.position.copy(point2);
    var direction = // What do I need here?
    footpath.rotation.y = direction;
    scene.add(footpath);
});

I am trying to figure out the correct rotation value for direction.

[UPDATE] The code by WestLangley has been helpful, but it doesn't work in all directions. I used the following code to calculate the length:

var length = footpaths[i].position.z - point2.position.z;

How can I ensure that the length works accurately in all directions?

https://i.sstatic.net/LfBua.jpg

Answer №1

In order to position a box between two 3D points, follow these steps:

var geometry = new THREE.BoxGeometry( width, height, length ); // ensure the length aligns with z-axis

geometry.translate( 0, 0, length / 2 ); // position one end at the origin

...

var box = new THREE.Mesh( geometry, material );

box.position.copy( point1 );

box.lookAt( point2 );

Using three.js version r.84

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

JavaScript causing values to disappear when the page refreshes

When a user hovers over ImageButtons, I use Javascript to change the ImageUrl. However, on submitting the form, the updated ImageUrl property is not reflected in the code behind. Similarly, I also dynamically update a span tag using Javascript, but its alt ...

Matching regex only on complete strings, not on parts of strings

My goal is to dynamically add and remove strings to a textarea when values in a table are clicked. The functionality should allow users to select and deselect values in the table, with the selected values adding or removing themselves from the textarea. It ...

developing a deferred commitment by utilizing promise objects

Hi everyone, I've encountered an issue with a JavaScript promise question that's throwing errors function delay(n) { return new Promise((resolve) => setTimeout(resolve, n*1000)); } The expected output should be "It is now 2 seconds later" ...

JavaScript: Exporting and Utilizing a Function within a Model.js File

Coming from a background in PHP OOP development, I am aware that there are various methods to create classes in JavaScript. I require assistance from a JavaScript developer to resolve this particular issue. Here is the situation: I am building an AWS lamb ...

Sequelize transforms any given date object into a local date representation

When running a query with a data replacement, the date is not set as UTC in the query. Here's the code snippet: let startInterval = moment('2020-12-09').toDate(); db.query(` SELECT kv.kpiId FROM kpiValues kv WHERE kv.insertDate ...

Merging two arrays together in JavaScript

Within my possession are two arrays: var g= [ { id: 36, name: 'AAA', goal: 'yes' }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { ...

Adding an HTML tag attribute to a Bootstrap 5 popover using the setAttribute() method: A Step-by

Trying to include HTML tags in a popover setAttribute() function within Bootstrap 5, but the tags are displayed as content rather than being applied as attributes. <button type="button" class="btn btn-secondary mx-2" data-bs-containe ...

What is the best way to send a function along with personalized data?

Currently, I am working on a project using node.js with socket.io. I am looking for a way to have socket.on() use a unique callback function for each client that joins the server. Here is my current technique: I have created a simple JavaScript class whi ...

Correcting the invalid syntax due to EOF issue

How can we resolve the end of file error? The brackets appear to be valid based on ecma standards, but it's not clear what is missing. After using jsonlint, this error was found: *Error: Parse error on line 16: ...States" }] }]}{ "i ...

Ensure that the view remains consistent while navigating a table that contains expanding concealed information

My table is dynamically populated with data within a div that has overflow: scroll and height set properties. The issue I face is that the data populates from the top, making it difficult to keep track of specific rows when scrolling within the #container ...

What is the best way to fetch HTML content using JavaScript?

I needed to incorporate JavaScript for fetching HTML code. I structured the HTML code in the following manner; <html> <div id="tesingCode"> <h1>Title</h1> <p>testOfCodetestOfCodetestOfCodetestOfCode</p> </div ...

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

Having Trouble with Your React.js Rendering?

I'm starting to learn React.js but I'm having trouble rendering it into the HTML. I can't figure out what's wrong. Any help would be greatly appreciated. Below are the HTML and JSX code: (Note: Full links to the react library are incl ...

Obtaining the complete JSON array in string format

I am currently using Fine Uploader to pass parameters in this way callbacks: { onSubmit: function(id, fileName) { this.setParams({ a: 'adm', b: '126', c: { fileID: id, ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Ensure that each child component receives a prop

Can you transfer a prop with a function to any child component? Specifically, I want to send a function from a parent component to each {children} element: <> <Navbar /> <main>{children}</main> <Footer /> </&g ...

Creating a dynamic shift in background color

Is it possible to use jQuery to slowly change the color of diagonal lines in a background styled with CSS, while also adding a fading effect? I have created a fiddle with the necessary CSS to display a static background. You can view it here: http://jsfid ...

Invoking a Jquery Dialog

Every time I click on the button to display a message, I encounter an issue where one MessageBox appears as expected. However, when I open the Jquery Dialog for the second time, two MessageBoxes pop up and the same problem occurs with three MessageBoxes on ...

Learn how to clear form values in react-bootstrap components

My objective upon clicking the register button is: Clear all input fields Hide any error tooltips Check out the CodeSandbox link I attempted to reset using event.target.reset();, but the tooltips persist on the screen. export default function App() { ...

Issues with zDepth functionality in Material-UI (React.js) not being functional

Can anyone explain the concept of zDepth to me? I have a component with the following render method: render() { return ( <div> <AppBar zDepth={2} title="Some title" iconElementLeft={<IconButton onClick={this ...