Expanding box geometry from a single side in Three.js

Just starting out with three.js and my first task was to create a box geometry that could be increased from only one side.

Issue : When increasing the width or height of an object, both sides automatically expand.

Check out this jsFiddle Example

I wasted an hour trying to find the correct algorithm:

    geometry = new THREE.BoxGeometry(strength, 200, 200);
    material = new THREE.MeshBasicMaterial({
        color: 0xff0000
    });

    mesh = new THREE.Mesh(geometry, material);
    mesh.applyMatrix( new THREE.Matrix4().makeTranslation( - strength + strength / 2, 0, 0 ) );

Could someone explain to me what exactly - strength + strength / 2 means? (If I increase strength by 1, shouldn't the translation be -1 instead of -0.5?)

What is the term for this type of algorithm and where can I find good resources to learn more about it as a beginner?

Answer №1

You have the option to adjust the geometry using the .translate() method, eliminating the need for a container object in the scene graph:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(2, 3, 5);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.GridHelper(10, 10));

var boxGeom = new THREE.BoxGeometry();
boxGeom.translate(0.5, 0.5, 0); // moving pivot point
var box = new THREE.Mesh(boxGeom, new THREE.MeshNormalMaterial());
scene.add(box);

var clock = new THREE.Clock();
var delta = 0;
var time = 0;

render();

function render() {
  requestAnimationFrame(render);
  delta = clock.getDelta();
  time += delta;

  box.scale.set(2.5 + Math.sin(time) * 2, 1.5, 1.5);

  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/95/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

Answer №2

Consider this alternative:

let obj = new THREE.Object3D();
let mesh = new THREE.Mesh(new THREE.BoxGeometry(1,1,1));
mesh.position.set(0.5,0.5,0.5);
obj.add(mesh);

scene.add(obj);

obj.scale.set(value,200,200);

Learn more about Scene Graphs here!

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

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

What is the best way to execute JavaScript on the main MVC page when an AJAX request in a partial view has finished?

My Asp.net MVC partial view is designed for searching and makes an Ajax call to retrieve results. After the results are displayed, the user can select a search result by clicking on a link in one of the rows. Upon selecting a search result, an Ajax post re ...

Do GPU-intensive animations get impacted by the CPU's load?

I have set up a special compositing layer for a div with the following unique styles: div { position: absolute; height: 50px; width: 50px; background: #900; top: 100px; left: 200px; will-change: transform; transform: translateZ(0); } Afte ...

The camera in ThreeJS is stationary and unable to be moved

I've been attempting to manipulate the camera's world matrix to move it, but unfortunately, it doesn't seem to be working. Regardless of what I try, the camera just won't budge. camera.matrixAutoUpdate = false camera.matrixWorld = port ...

Verify the MAC address as the user types

I need to verify a form field for MAC Addresses and have implemented the following code that does the job. $('body').on('keyup', '#macAddess', function(e){ var e = $(this).val(); var r = /([a-f0-9]{2})([a-f0-9]{2})/i, ...

What is the best way to populate empty dates within an array of objects using TypeScript or JavaScript?

I am trying to populate this object with dates from today until the next 7 days. Below is my initial object: let obj = { "sessions": [{ "date": "15-05-2021" }, { "date": "16-05-2021" }, { "date": "18-05-2021" }] } The desired ...

Feeling uncertain about Node, NPM, Bower, and how to set them up for Bootstrap?

Looking to expand my knowledge in web development, I have a solid understanding of HTML, JS, CSS, and server-side programming. However, the concepts of Nodejs, npm, and Bower are still unclear to me. In order to begin a new project, I created a designated ...

What is the best situation to utilize $(document).ready()?

After observing that using $(document).ready(..) seems to introduce a noticeable delay in applying JavaScript effects, I've been contemplating the best approach. I know that simply placing the effect in a <script> tag may not work if the DOM isn ...

Managing State with Vuex: Storing Getter Results in the State

I'm encountering an issue with my Vuex.Store: My goal is to retrieve an object (getter.getRecipe) by using two state entries as search criteria (state.array & state.selected) through a getter. Then, I want to store the outcome in my state (state. ...

Obtain access to the DOM element using template reference variables within the component

Searching for a method to obtain a reference to the DOM element for an Angular 2 component through a template reference variable? The behavior differs when working with standard HTML tags versus components. For example: <!--var1 refers to the DOM node ...

Interactive canvas artwork featuring particles

Just came across this interesting demo at . Any ideas on how to draw PNG images on a canvas along with other objects? I know it's not a pressing issue, but I'm curious to learn more. ...

Exploring the Applications of Directives in Multiple Modules within Angular 2

When I declare the directive in two modules, I get an error that says Type PermissionDirective is part of the declarations of 2 modules. However, when I declare it in only one module, I receive an error stating Can't bind to 'isPermission' s ...

Issue with Click event not functioning properly following an ajax request in a dynamic element within the Backbone framework

I have successfully implemented a dynamic popup in my Backbone.view through the click of a button: var Section = Backbone.View.extend({ className: 'sqs-frontend-overlay-editor-widget-section', events:{ 'click .sqs--section--control__ed ...

Discovering the bottom side of a cube using Euler Angles (or Quaternions) in three.js

Hey there! I have a little puzzle that I could use your help with: Imagine this - I've got a cube that can be rotated around three different axes. I've gathered some data on the cube's rotation, specifically an array of three angles rangi ...

Why is it that my website in React crashes when I type rapidly in the TextField component?

Whenever I input text quickly into the TextField in my app, it causes my website to crash and display a blank white screen. Below is the snippet of code causing the problem: TextField Code: <TextField label="Item name" ...

Importing a MATLAB table file into a Node.js environment and converting it into an array

Currently in the process of setting up a test server for a Web-Application, where fake data needs to be transmitted via a Websocket. The fake data is stored in a MATLAB table file (.mat), which essentially consists of a 4000*192 array. My goal is to conver ...

What is the best way to prioritize loading JSON models first in three.js and declare a variable before initializing?

I am looking to efficiently load multiple JSON models and store them in global variables for easy access. This will streamline tasks like copying, translating, and more without the need to reload a model each time. After trying various methods, I have not ...

Include a personalized header in $http

In my factory, I have multiple functions that follow this structure: doFunction: function () { return $http({ method: 'POST', url: 'https://localhost:8000/test', data: {}, headers: { "My_Header" ...

You must use the 'new' keyword in order to invoke the class constructor

Although similar questions have been asked before, my situation differs from the typical scenarios. I have a basic base class named CObject structured as follows: export class CObject extends BaseObject { constructor() { super(); } sta ...

Having trouble with the tooltip feature in Bootstrap?

I've searched high and low, including on this site! I've experimented with all sorts of code, but nothing seems to make the tooltips function in BootStrap. It's beginning to really frustrate me!! Does anyone happen to have the working js co ...