Creating a 3D rectangle using three.js with box2d rectangle rendering

When it comes to rendering box2d bodies on the canvas, a common issue arises. Box2d provides us with the center of the body and its angle, while the canvas draws shapes like rectangles from the top-left corner. I encountered this problem but managed to find a solution by following tutorials from Seth Land. Here's the code snippet that helped me address this challenge:

g.ctx.save();
g.ctx.translate(b.GetPosition().x*SCALE, b.GetPosition().y*SCALE);
g.ctx.rotate(b.GetAngle());
g.ctx.translate(-(b.GetPosition().x)*SCALE, -(b.GetPosition().y)*SCALE);
g.ctx.strokeRect(b.GetPosition().x*SCALE-30,b.GetPosition().y*SCALE-5,60,10);
g.ctx.restore();

In the above code, b represents the body, SCALE is the canvas-pixel/box2d-meters converter, and 60 and 10 are the dimensions of the rectangle (half dimensions being 30 and 5).

_

The Challenge Ahead

Now, my goal is to render this in three.js. The initial hurdle is that three.js works in 3D while box2d operates in 2D. However, I aim to create a 3D rectangle on top of the existing 2D structure. I want to retain the 2D axis dimensions from box2d and introduce an arbitrary third dimension.

While my project doesn't necessitate 3D physics, I desire to add thickness to these 2D objects in the third dimension. How can I achieve this? My attempts so far have been as follows:

   // Top-down perspective
    camera.position.set(0,1000,0);
    camera.rotation.set(-1.5,0,0);

    geometry = new THREE.CubeGeometry(200, 60, 10, 1, 1, 1);

    // Obtain b as box2d rectangle
    loop(){
    mesh.rotation.y = -b.GetAngle();
    mesh.position.x = b.GetPosition().x*SCALE;
    mesh.position.y = -b.GetPosition().y*SCALE;
    }

Regrettably, this approach doesn't replicate the box2d debug draw accurately. The value of -1.5 for camera rotation does not provide the desired 90-degree angle turn (if someone knows the correct value, please share). Additionally, the three.js rectangle fails to align with the movements of box2d, similar to the issues faced with standard canvas before implementing context translations and rotations.

I am hopeful that someone can offer insights into a potential solution. Thank you in advance! :)

EDIT: It appears that someone has already accomplished this feat (requires WebGL on Chrome): http://serv1.aelag.com:8082/threeBox

The second link showcases spheres, so there are no challenges with rotation mapping between box2d and three.js. The first link includes cubes and rectangles, which aligns with what I am aiming to achieve.

Answer №1

What kind of camera do you have?

To achieve a "2D" effect, it is essential to use an Orthographic camera. Using any other type of camera may result in perspective-projection, causing discrepancies between the 2D image and what you see on screen.

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

What is the process for customizing the arrow of a <select> dropdown menu exclusively?

Here is the code for a dropdown menu: <select id="dropdown"> <option value="">Go to page...</option> <option value="http://stackoverflow.com">CSS-Tricks</option> <option valu ...

The Javascript navigation bar is not displaying properly on mobile devices as it should

After customizing the responsive navbar tutorial from W3Schools using CSS and JS, I encountered an issue. I wanted to include a logo and a web page title before the navbar, which worked perfectly when the webpage was maximized. However, when I resized the ...

"Why is it that when the form is submitted, only half of your React component's props are undefined

Just starting out with React, and I'm hoping this issue isn't too obvious. I've been struggling with it for a while now. When looking at the React Dev Tools in Chrome, all of the form's props are defined and appear as expected, even af ...

Transmission of JSON to a C# controller via AJAX results in a Count value of zero in .NET 7

Whenever I attempt to send a JSON object to my controller, the parameter isn't being received. This is the JavaScript code snippet: var input = document.getElementById("input"); input.addEventListener('change', function () { const read ...

What could be causing my php code to fail to trigger an alert when using Ajax technology?

As a novice in web programming, I have successfully created a website but now I am facing challenges while trying to integrate a database. Despite having everything properly set up, my ajax function doesn't seem to be working and I can't figure o ...

When working with Vue in Laravel, the console may show that app.message is returning undefined

Recently, I embarked on my journey to learn Vue and have been closely following their introductory guide. However, I seem to be facing a hurdle at this point: Simply open your browser’s JavaScript console and adjust app.message to a different value. I ...

Tips for preventing multiple requests in your JavaScript search autocomplete feature

I'm currently using the Turbolinks.visit action with the help of $(document).on("input");... HTML <form id="mainSearch" method="get" autocomplete="off"> <input type="search" name="s" placeholder="Search" /> </form> Javascript ...

When attempting to access elements using document.getElementById() in a React application

I've been struggling to access the canvas element in my code using document.getElementById('canvas'), but it just won't cooperate. Can anyone lend a hand? I've spent the past week scouring for a solution, but to no avail. import Re ...

Utilizing Chart.js for generating a sleek and informative line graph

After executing a MySQL query, I obtained two tables named table1 (pl_pl) and table2 (act_act) with the following data: table1: label act_hrs Jan-19 7 Feb-20 8 Mar-20 9 table2: label pl_hrs Mar-20 45 Apr-20 53 I am looking to create a line cha ...

React Native: Avoiding Infinite Loops in useEffect

I am facing an issue where my app goes into an infinite loop because pointsData is inside the useEffect function. How can I resolve this situation? function useGetPoints() { const [pointsData, setPointsData] = useState<PointTbleType[]>([]); ...

What steps should I take to ensure that my Ngrok domain is functioning properly?

Screenshot of Endpoints I've been facing challenges while attempting to get my NGROK domain operational. Despite completing all the necessary setup steps and successfully running multiple tunnels simultaneously with NSSM, as well as having a business ...

Exploring Azure: Obtain a comprehensive list of application settings from a deployed Node.js web application

After successfully deploying a NodeJs app to a Linux Azure AppService, I am now aiming to retrieve the server settings of this particular app-service. By enabling managed Identity for the AppService under the 'Identity' tab, I attempted to achiev ...

Calculate the total value of fields in the final stage of an aggregate MongoDB query

I have created an aggregation pipeline to connect Parent and Children Collections in order to gather related data. The goal is to calculate the total number of sodas all children have collectively. Using the projection stage, I am able to extract specific ...

Arranging an array of objects by their unique identifiers

Given an array of objects containing root and list elements in a tree structure, how can I efficiently organize them into a tree with an unknown depth? Each object has a parent element ID property. I am currently working on building a menu. While I have s ...

Tips for capturing all mobile events in Angular

Trying to capture all mobile events like touch and swipe, I have added event listeners at the document level: document.addEventListener('tap', trackTouchActivity, false); document.addEventListener('swipe', trackTouchActivity, false ...

Adjust the fixed navbar position in MaterializeCSS as you scroll

First of all, I apologize for my limited proficiency in English. I have a website with a company logo at the top and a navigation bar below it. My goal is to change the position of the navigation bar to the top when scrolling past the company logo. I att ...

The user interface does not get refreshed right away; it only shows the changes after the

Here is an example of HTML: <div ng-repeat="user in controller.users"> <p>{{user.name}}</p> <button ng-click="controller.deleteUser(user)" value="delete"></button> </div> Next, we have the controller code: vm ...

Ways to include external JavaScript in an HTML document along with CSS styling

Check out this code snippet in HTML with embedded JavaScript. I'm trying to externalize the JS file, but it's not functioning as expected when I do so. How can I resolve this issue and ensure that the element moves upon clicking when the script i ...

Avoiding the default action to submit AJAX form data won't result in any changes to the front end?

Currently, I am working with Flask and have utilized JavaScript to prevent default behavior in order to send all the necessary data through an AJAX request. However, I am facing an issue where although my view contains all the data (verified by console out ...

Trouble hindering mouseup event on Android despite using preventDefault()

Seeking a solution to prevent a mouseup or touchend event from firing twice. See the complete example below: <!DOCTYPE html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script& ...