Achieve the proper angle and rotation along the y axis

If I wanted to add a tetrahedron to my three.js scene and ensure that its bottom face is flat, as well as reset the y axis for correct rotation around it, how can I achieve this?

// Creating a dummy object
var dummy = new THREE.Mesh( new THREE.CubeGeometry( 1, 500, 1 ), new THREE.MeshBasicMaterial() );
dummy.position.x = 0;
dummy.position.z = 0;
scene.add( dummy );

// Creating the tetrahedron
var points = [
new THREE.Vector3( 200, 0, 0 ), //bottom right
new THREE.Vector3( 0, 200, 0 ), //top
new THREE.Vector3( 0, 0, 200 ), //bottom left
newTHREE.Vector3( 200, 200, 200 ) //bottom back    
];

object = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials );

object.position.set( -110, 0, -110 );
object.rotation.set( 0.7, 0.0, -0.7 );

dummy.add( object );

Answer №1

@WestLangley, I stumbled upon that post a few hours before your response and managed to implement it successfully (shown below). However, I must admit that the mathematical concepts behind makeRotationAxis() and the necessity of an offset of -115 on the x and z axes for

tetrahedron.position.set( -115, 0, -115 )
still elude me when dealing with a tetrahedron encompassing 200 vectors. The journey involved a fair amount of trial and error; hence, it would be greatly beneficial if I could grasp the underlying calculations to modify sizes effortlessly.

<!-- language: lang-js -->
<!DOCTYPE html>
<html lang="en">
<head>
    <title>three.js webgl - convex geometry</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <style>
        body {
            font-family: Monospace;
            background-color: #000;
            margin: 0px;
            overflow: hidden;
        }

        canvas { width: 500px; height: 500px }
    </style>
</head>
<body>

    <script src="three.min.js"></script>
    <script src="js/geometries/ConvexGeometry.js"></script>
    <script src="js/Detector.js"></script>

    <script>

        if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

        var container;
        var camera, scene, renderer;

        init();
        animate();

        function init() {

            container = document.createElement( 'div' );
            document.body.appendChild( container );

            camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
            camera.position.y = 400;

            scene = new THREE.Scene();

            var light, object, materials;

            scene.add( new THREE.AmbientLight( 0x404040 ) );

            light = new THREE.DirectionalLight( 0xffffff );
            light.position.set( 0, 1, 0 );
            scene.add( light );

            materials = [
                new THREE.MeshLambertMaterial( { color: 0xffffff, wireframe: false, transparent: false, opacity: 0.5, wireframeLinewidth: 2, wireframeLinejoin: "miter" } )
            ];

            //dummy line object
            var dummy = new THREE.Mesh( new THREE.CubeGeometry( 1, 500, 1 ), new THREE.MeshLambertMaterial() );
            dummy.position.x = 0;
            dummy.position.z = 0;
            scene.add( dummy );

            //tetrahedron points
            var points = [
                new THREE.Vector3( 0, 0, 200 ), //bottom right
                new THREE.Vector3( 0, 200, 0 ), //top
                new THREE.Vector3( 200, 0, 0 ), //bottom left
                new THREE.Vector3( 200, 200, 200 ) //bottom back

            ];          

            tetrahedron = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials );

            //fix the rotation so that the point of the tetrahedron points up
            tetrahedron.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3( 1, 0, -1 ).normalize(), Math.atan( Math.sqrt(2)) ) );

            //fix the offset
            tetrahedron.position.set( -115, 0, -115 );

            //add the tetrahedron to the dummy line object
            dummy.add( tetrahedron );

            renderer = new THREE.WebGLRenderer( { antialias: true } );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            container.appendChild( renderer.domElement );

            window.addEventListener( 'resize', onWindowResize, false );

        }

        function onWindowResize() {

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );

        }

        function animate() {

            requestAnimationFrame( animate );

            render();
            stats.update();

        }

        function render() {

            var timer = Date.now() * 0.0001;

            camera.position.x = 800;
            camera.position.y = 500;
            camera.position.z = 800;

            camera.lookAt( scene.position );

            for ( var i = 0, l = scene.children.length; i < l; i ++ ) {

                var object = scene.children[ i ];
                object.rotation.y = timer * 2.5;

            }

            renderer.render( scene, camera );

        }

    </script>

</body>

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

Waiting for PHP's return value in JavaScript using AJAX

I am new to AJAX and my objective is to open a PHP file using JavaScript. function verifyInput(user, solution) { return fetch("validateSolution.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded; ch ...

The code is running just fine when tested locally, but it seems to encounter an issue when accessed remotely, yielding

Currently, I am in the process of developing a dual twin setup using a Raspberry Pi. The goal is to simulate a continuous transmission of body temperature data, which is then sent to a server that stores the information in a MongoDB database. Everything fu ...

Multi-Slide AngularJS Carousel

My current setup includes a carousel like so: <div> <carousel id="myC" interval="3000" > <slide ng-repeat="order in orders"> <img ng-src="whatever.jpg" style="margin:auto;"> <div ...

Toggling with Jquery when an image is clicked

I'm trying to wrap my head around the functionality of jquery toggle. My goal is to toggle to the next anchor element with the class plr-anchor when an image with the class go_down is clicked. The information is being populated using maps. Javascript ...

Create a PHP array that mirrors the structure of a JSON document

My PHP skills are a bit rusty and I could use some advice or help. I am attempting to create a basic API that can provide JSON data for populating a JavaScript chart. Using PHP, I am querying a database to retrieve statistics by month/year. However, I am ...

Animating elements within Firefox can sometimes cause adjacent elements to shift positions

Currently, I am working on a single-page website that utilizes keyboard-controlled scrolling. To achieve the desired scroll effect, I have developed a JavaScript function that animates divs. Here is the JavaScript code: var current_page = "#first"; func ...

How to use jQuery to update the href attribute of a parent link

Can someone help me figure out why I am having trouble changing the 'href' of the parent link to a header logo? Thank you in advance! Here is the HTML code snippet: <a href="https://URL.IWANTO.CHANGE"> <img id="partner_logo" src="/ ...

Unable to upload image to Cloudinary due to the following error: ENOENT - the file or directory does not exist

While attempting to upload images and save them in the public/upload_files folder using Postman, I encounter the following error: <body> <pre>Error: ENOENT: no such file or directory, open &#39;storage/media/1637741568809.png&#39;</p ...

Locating the exact position of a DOM node within the source document

Purpose In the process of creating a series of 'extractor' functions to identify components on a page using jsdom and nodejs, I aim to organize these identified 'component' objects based on their original placement within the page. Ch ...

The AJAX callback is unable to access the method of the jQuery plugin

I have a scenario where I am fetching data from an AJAX response and attempting to update a jQuery plugin with that value within the success callback: $.ajax({ url: '/some/url', type: 'GET', dataType: 'json', succ ...

Converting TypeScript to ES5 in Angular 2: A Comprehensive Guide

I am currently diving into Angular 2 and delving into Typescript to create simple applications within the Angular 2 framework. What I have discovered is that with Typescript, we can utilize classes, interfaces, modules, and more to enhance our application ...

Tips for connecting 2 Bootstrap 5 carousels

I currently have 2 Bootstrap 5 carousels (carousel-a & carousel-b) on the same page and I want them to be synchronized with each other. I believe this can be achieved using JavaScript, but I am not very familiar with it. Below is the structure of carousel- ...

Error: Unspecified object found in Three.js file

I am facing an issue where I have declared a global variable to store an OBJ loaded through THREE.OBJLoader, but when trying to animate the position or rotation of the object, I receive an error stating that the variable is undefined. Below is how I have ...

I am encountering issues with my PostCSS plugin not functioning properly within a Vue-cli 3 project

I developed a custom postcss plugin that was working perfectly according to the postcss guidelines until I tried to implement it in a real project. For reference, here's the plugin on GitHub My goal is to integrate it into a Vue-cli app using Webpac ...

Transform the date to match the user's preferred timezone abbreviation

I am currently utilizing the momentJS library for timezone conversion logic within my JavaScript code. I retrieve the User Preference Timezone abbreviation from a web service response, but when attempting to convert the date using the Timezone abbreviation ...

Transforming all commas to plus signs in a JavaScript codebase for the entirety of

Currently, I am using winston for logging and have created a common method to log throughout the project. However, I am facing an issue with many logging statements that look like this: logger.info("here is the data" , data) The problem arises when trying ...

Navigating a vast code repository in Node.js

As I prepare to start a Node.js project with a sizable codebase, my aim is to keep my code isolated from the node_modules directory. I am keen on utilizing namespaces and organizing my code into folders for better management. However, it seems like I woul ...

Expanding the dimensions of $state.store.object within a vue.js application

As I delve into learning Vue.js, I've noticed that the application I'm currently developing fetches data from a database and then organizes it into a list before binding and displaying it on the page. Here's a snippet of the code where this ...

VueJS can manipulate an inline template by dynamically changing its content and reinitializing

this particular query shares similarities with the discussions on VueJS re-compiling HTML in an inline-template component as well as How to implement Vue js directive in an appended html element Regrettably, the approach suggested in those threads is no l ...

Impressive javascript - extract file from formData and forward it

Presented here is my API handler code. // Retrieve data. const form = formidable({ multiples: true }); form.parse(request, async (err: any, fields: any, files: any) => { if (!drupal) { return response.status(500).send('Empty ...