Guide to Producing an Unorthodox 3D Polygon Extruded Form using React-Three-Fiber

Up until now, I've only utilized useBox statement to create 3D rectangles. Is there a method available to generate something like a wooden piece in dimensions of "two by four" with cut ends at specific angles, akin to the image shown below?

https://i.sstatic.net/XfHu3.png

You can find the code/demo here: https://codesandbox.io/s/ragdoll-physics-forked-bntr9?file=/src/index.js

The issue seems to be that I'm combining different samples from Three.js and React-Three-Fiber.

After watching this video https://youtu.be/3eGeh_aJxMI?t=509, it got me thinking whether I could develop a 2D polygon shape and then extrude it into 3D space. If there's a more effective approach, please share your insights. The video uses 'scene.add', but as I'm working with react-three-fiber, I assume I need to modify that part to suit my existing canvas setup.

The following example doesn't depict the exact shape I desire; it's just an initial demo showcasing a triangle extruded into 3D (the video showcased a heart shape).

I'm unsure about which element should be used in the return statement. Using "", or "" resulted in errors (I can provide a list of errors if needed, but considering they might not be the correct elements, I'll omit them for now). When using lowercase "", the code runs without errors, yet the 3D extruded triangle object isn't visible on the display.

const Truss1 = () => {
  var trussPosition = [5, 5, 5];
  const trussBoard1FlatShap = new Shape();

  const x = 0;
  const y = 0;
  const moveSize = 40;
  trussBoard1FlatShap.moveTo(x - moveSize, y - moveSize);
  trussBoard1FlatShap.lineTo(x + moveSize, y - moveSize);
  trussBoard1FlatShap.lineTo(x, y + moveSize);

  var extrudeSettings = { amount: 30, bevelEnabled: false };
  var extrudeSettings2 = {steps: 2,
    depth: 16,
    bevelEnabled: true,
    bevelThickness: 1,
    bevelSize: 1,
    bevelOffset: 0,
    bevelSegments: 1}
  var material = new MeshLambertMaterial({ color: 'red'});

  var trussBoard1Extruded = new ExtrudeGeometry(trussBoard1FlatShap, extrudeSettings);  
   // I also tried extrudeSettings2 from above. 
  var trussBoard1Mesh = new Mesh(trussBoard1Extruded, material);
  trussBoard1Mesh.position.z = 55;
  
  const [cube] = useBox(() => ({ type: 'Static', position: [0, -3, -9.8], args: [0.25, 2, 0.25] }))

  return (
       <>
           <mesh scale={[8, 8, 8]} ref={trussBoard1Mesh} > 
           </mesh> 
           <Box scale={[1, 1, 1]} ref={cube} > 
           </Box> 
       </>
    )
}
    ...
    ReactDOM.render(
      <Canvas style={{ cursor: 'none' }} shadows orthographic camera={{ position: [-25, 20, 25], zoom: 25, near: 1, far: 100 }}>
        <CameraControls />
        <color attach="background" args={['#171720']} />
        <fog attach="fog" args={['#171720', 20, 70]} />
        <ambientLight intensity={0.2} />
        <pointLight position={[-10, -10, -10]} color="red" intensity={1.5} />
        <Physics iterations={15} gravity={[0, -200, 0]} allowSleep={false}>
          <Plane position={[0, -5, 0]} rotation={[-Math.PI / 2, 0, 0]} />
          <Lamp />
          <Table />
          <DynTable>{/* <texture  attach="map" image={'/images/wood_andrey-haimin-q2Fyzn-KJOQ-unsplash.jpg'} /> */}</DynTable>
          <DynShed />
          <Truss1 />
        </Physics>
      </Canvas>,
      document.getElementById('root')
    )

Answer №1

After hiring a freelancer, I received the following custom code:

function Truss1() {
  var length = 14,
    width = 2,
    deg = 10,
    thickness = 0.3
  var rad = (deg * Math.PI) / 180
  var offset = Math.min(Math.tan(rad) * width, length / 2)
  var shape = new Shape()
  shape.moveTo(0, 0)
  shape.lineTo(offset, width)
  shape.lineTo(length - offset, width)
  shape.lineTo(length, 0)
  shape.lineTo(0, 0)
  const extrudeSettings = {
    curveSegments: 1,
    steps: 1,
    depth: thickness,
    bevelEnabled: false
  }

  return (
    <mesh>
      <extrudeBufferGeometry attach="geometry" args={[shape, extrudeSettings]} />
      <meshStandardMaterial color="red" side={DoubleSide} />
    </mesh>
  )
}

Sample Output from a specific viewpoint: https://i.sstatic.net/KoPUC.png

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

Enhancing x-axis presentation in D3.js-generated charts

I created a bar chart using D3.js, but I have encountered an issue with one of the values on the x-axis being too long. I attempted to use CSS properties like text-overflow: ellipsis, width: 10px, and overflow: hidden to abbreviate values that exceed a cer ...

Dividing a string using regex to deal with numerical issues

My task involves processing a list of strings that look like this: Client Potential XSS2Medium Client HTML5 Insecure Storage41Medium Client Potential DOM Open Redirect12Low The goal is to split each string into three parts, like so: ["Client Potential X ...

The event to close the HTTP connection in the Node server always triggers

I want to set up a close event that triggers before the server shuts down. To achieve this, I have implemented the following code: var express = require('express'); var app = express(); var http = require('http').Server(app); var list ...

The <a href="#divtagid"> link is incapable of triggering the opening of the div tag when called from JavaScript

I need help with displaying the content of a div with the id "hello" in maindiv when clicking on the href "Click Here", but it's not working as expected. Here is the code I have: $(document).ready(function() { var newhtml = '<a href="#he ...

The canvas doesn't seem to be rotating even after executing the setTransform

Within my HTML5 canvas, I have been experimenting with drawing lines and rotating them around the center point. My goal is to reset the canvas's transformation each time I draw, followed by re-translating/rotating the canvas. However, I have encounter ...

Experiencing difficulties with parsing JSON data and storing values in a database

I received a JSON response from the server and need help saving the values in a MySQL database using PHP. Can someone please assist me with this? {"fields":[{"label":"Do you have a website?","field_type":"website","required":false,"field_options":{}," ...

`"Unable to execute the 'ng build --env=prod' command"`

I have a JavaScript website that I need to rebuild with some changes I made. In order to build the application, I was instructed to run this command from the source files directory: ng build –env=prod However, when I try to do so, I keep encountering t ...

Firebase Functions: Your functions are missing a definition

I have the following code in index.js: exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onCreate((snapshot, context) => { // Fetch the current value written to the Realtime Database. const original = snapshot. ...

What is the best method for creating thumbnail URLs for video files in HTML with JavaScript?

I am facing an issue with generating a thumburl for uploaded video files. After dynamically creating an input file and uploading local video files, I am able to retrieve the name and size of the file along with other information as shown in the screenshot ...

The beauty of asynchronous GET requests in VueJS

As a newcomer to VueJS, I am exploring how to make a GET request to the GitHub API. Initially, I made a request to sort users by follower count, resulting in an array ordered in descending order of user logins. Following that, I sent another GET request to ...

Is it feasible to verify for vacant dates with a single click?

Is there a way to determine if a date value is empty, and if it is, display a popup indicating so? After some research, I stumbled upon a similar issue where the date value was always filled with a default "mm/dd/yyyy" value. The solution provided involv ...

What is the best way to remove input focus when clicked away?

I am in the process of developing an application using next js, and I need assistance with designing a search field. The primary functionality I am looking to implement is displaying search suggestions when the user starts typing, but hiding them when the ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

Preventing template rendering in Angular until an event is triggered - but how?

I am currently working on a directive that functions well, but I had to resort to using inline template code in order to delay rendering until the click event occurs. However, I believe it would be more streamlined if I could assign the directive template ...

Angular BehaviorSubject is failing to emit the next value

I am facing an issue with a service that uses a Behavior subject which is not triggering the next() function. Upon checking, I can see that the method is being called as the response is logged in the console. errorSubject = new BehaviorSubject<any> ...

Leveraging AJAX with React Router

Currently tackling a project utilizing React Router, encountering some challenges with data flow. Each page triggers an AJAX call to fetch data for the component. These calls have been placed within componentDidMount: // The following code is in ES6 comp ...

Getting to the values within a JSON object that contains multiple arrays

Is there a way to retrieve array data from the json object data? const [data, setData] = useState([]) const getData = () => { axiosInstance .get(url + slug) .then(result => setData(result.data)) } useEffect(() = ...

Unable to trigger dispatchEvent on an input element for the Tab key in Angular 5

In my pursuit of a solution to move from one input to another on the press of the Enter key, I came across various posts suggesting custom directives. However, I prefer a solution that works without having to implement a directive on every component. My a ...

The menu options pulled from a JSON file generated on the server using Nextjs are not showing up in the HTML source code

Apologies if the title is a bit unclear. Let me try to explain: my website is built using Next.js and retrieves data from Sanity Studio (CMS). In Sanity, users can create menu items which are displayed in the footer component, sidebar component, and header ...

An unexpected identifier error occurred following an Ajax request

Below is the HTML code that I am working with: <div id="texttheory" class="centertext">'. $short .' </div>'; <button id="thbutton" class="theory_button" onclick="javascript:changetheory('.$long.')"> <im ...