I have a ThreeJS scene with 16 objects that are supposed to end up in a 4 by 4 square grid. However, when I run the code, I only see one of the objects. I wrote a "dump" function to show me all the current XYZ values of the mesh objects's position property, which you can see below. The values all look good to me and I believe I should see a nice 4 by 4 square grid of objects given the positioning those values present.
I am using this ThreeJS Javascript file for ThreeJS:
https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js
I am using this code to create the mesh. The mesh is a cube with initially the side facing the camera is a cat image:
function makeCatCube(catImageUrl, textureBackSide, locX, locY, locZ) {
let errPrefix = '(makeCatCube) ';
// TODO: Should we use BoxBufferGeometry here for greater speed?
let cubeGeometry = new THREE.BoxGeometry(2, 0.1, 2);
let loader = new THREE.TextureLoader();
let materialArray = [
new THREE.MeshBasicMaterial( { map: loader.load('/images/cards/white-square-400x400.png') } ),
new THREE.MeshBasicMaterial( { map: loader.load('/images/cards/white-square-400x400.png') } ),
// Card face.
new THREE.MeshBasicMaterial( { map: loader.load(catImageUrl) } ),
// Card back side.
new THREE.MeshBasicMaterial(
{
map: textureBackSide
}
),
new THREE.MeshBasicMaterial( { map: loader.load('/images/cards/white-square-400x400.png') } ),
new THREE.MeshBasicMaterial( { map: loader.load('/images/cards/white-square-400x400.png') } ),
];
cube = new THREE.Mesh( cubeGeometry, materialArray );
if (g_ShowGraphicsDebugInfo) {
console.log(errPrefix + `Setting cube position to - X: ${locX}, Y: ${locY}, Z: ${locZ}`);
}
cube.position.set(locX, locZ, locY);
// TODO: Magic number to set the cube's X rotation so it looks flat facing the viewer.
cube.rotation.x = THREE.Math.radToDeg(60);
return cube;
}
Here is the main promise that builds all the game assets and shows where I add the mesh objects to the scene. The global g_aryCatCards array that contains all the cat cards that were built is prepared in a much larger module elsewhere. It contains each of the cat cards and each card has a meshThreeJS property that contains the ThreeJS mesh object (i.e. - the cube) that was built using the makeCatCube() function shown above :
function initializeGameAssets_promise(gameAreaDomElementID, threeJSCanvasAreaDomElementID, catCardWidth, catCardHeight) {
let errPrefix = '(initializeGameAssets_promise) ';
return new Promise(function(resolve, reject) {
try {
buildAllCatCards_promise(gameAreaDomElementID, threeJSCanvasAreaDomElementID, 1, catCardWidth, catCardHeight)
.then(result => {
g_Scene = new THREE.Scene();
g_Scene.background = new THREE.Color('yellow');
initCamera();
initRenderer();
for (let cardLabelKey in g_aryCatCards) {
let catCard = g_aryCatCards[cardLabelKey];
g_Scene.add(catCard.meshThreeJS);
}
let threeJSCanvasAreaDOMElement = document.getElementById(threeJSCanvasAreaDomElementID);
if (!threeJSCanvasAreaDOMElement)
throw new Error(errPrefix + `Unable to find the DOM element for the cat cards underlay table using ID: ${threeJSCanvasAreaDomElementID}`);
threeJSCanvasAreaDOMElement.appendChild(g_Renderer.domElement);
let catCardsTableElementOffset = getElementOffsetById(ELEMENT_ID_CAT_CARDS_TABLE);
threeJSCanvasAreaDOMElement.left = catCardsTableElementOffset.left;
threeJSCanvasAreaDOMElement.top = catCardsTableElementOffset.top;
// Start the rendering process.
render();
resolve(true);
})
.catch(err => {
reject(err);
});
}
catch(err) {
reject(err);
}
});
}
Here are the functions I use to initialize the camera and the renderer:
function initCamera() {
g_Camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
g_Camera.position.set(0, 3.5, 5);
g_Camera.lookAt(g_Scene.position);
}
function initRenderer() {
g_Renderer = new THREE.WebGLRenderer(
{
antialias: true
});
}
This dump shows the XYZ values of the mesh object's position property:
------------- DUMPING MESH POSITIONS -------------
[label: A1] - X: 2, Y: 0, Z: 2
[label: A2] - X: 176, Y: 0, Z: 2
[label: A3] - X: 350, Y: 0, Z: 2
[label: A4] - X: 525, Y: 0, Z: 2
[label: E1] - X: 2, Y: 0, Z: 364
[label: E2] - X: 176, Y: 0, Z: 364
[label: E3] - X: 350, Y: 0, Z: 364
[label: E4] - X: 525, Y: 0, Z: 364
[label: L1] - X: 2, Y: 0, Z: 183
[label: L2] - X: 176, Y: 0, Z: 183
[label: L3] - X: 350, Y: 0, Z: 183
[label: L4] - X: 525, Y: 0, Z: 183
[label: X1] - X: 2, Y: 0, Z: 545
[label: X2] - X: 176, Y: 0, Z: 545
[label: X3] - X: 350, Y: 0, Z: 545
[label: X4] - X: 525, Y: 0, Z: 545
I really don't know what to do at this point to debug this problem. Can anyone give me some general tips on what to inspect, or what diagnostic code I could write to try and figure this out?
Your camera can only see 9 units deep
new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
but your objects are up to 545 units away
Try
const near = 1;
const far = 1000;
new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, near, far);
see
You also seem to have the camera looking in the wrong direction.
g_Camera.position.set(0, 3.5, 5);
g_Camera.lookAt(g_Scene.position);
AFAIK g_scene.position is 0, 0, 0 which means the camera is at z = 5 looking toward Z = 0 but your list of objects are almost all behind the camera.
Try
g_Camera.position.set(0, 3.5, -50);
g_Camera.lookAt(g_Scene.position);
Related
I am trying to extrude rectangle along a curve path. Problem here is the shape is twisting for various curves. Is there a way where irrespective how curve bends, it will always extrude shape in same orientation i.e it should not twist shape.
The end result are different. Here I wish to draw uniform rectangle orientation. If it is a feature behaviour like this, how should I approach for a work around to make shape orientation uniform.
<html>
<head>
<title>Extruded Buffer Issue along path</title>
<meta charset="utf-8" />
<meta name="author" content="Vishal D" />
<style>
body {
margin: 0px;
border: 1px blue solid;
}
</style>
</head>
<body>
<script type="module">
import * as THREE from "./three.module.js";
import { OrbitControls } from "./OrbitControls.js";
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
10000
);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
const size = 2000;
const divisions = 100;
const gridHelper = new THREE.GridHelper(size, divisions);
scene.add(gridHelper);
// Add shape 1
const rawPoints1 = [
{ x: -811.4902770929039, y: -1401.3931087367237, z: 80.33 },
{ x: -810.239964377135, y: -1402.0211585126817, z: 81.08 },
{ x: -804.0070621669292, y: -1404.9163141585886, z: 81.31 },
{ x: -796.6638076193631, y: -1408.3935632109642, z: 81.58 },
{ x: -790.4402361027896, y: -1411.441899254918, z: 81.81 },
{ x: -779.4486810080707, y: -1416.9871105961502, z: 82.21 },
{ x: -771.4336166419089, y: -1421.1996304765344, z: 82.51 },
{ x: -767.3094508089125, y: -1423.405458174646, z: 82.66 },
{ x: -757.7921450398862, y: -1428.5523871444166, z: 83.01 },
{ x: -755.1702206097543, y: -1429.9923011995852, z: 83.73 },
];
const points1 = [];
rawPoints1.forEach((point) => {
points1.push(new THREE.Vector3(point.x + 800, point.z, point.y + 800));
});
const randomSpline = new THREE.CatmullRomCurve3(points1);
const extrudeSettings = {
steps: 30,
bevelEnabled: false,
extrudePath: randomSpline,
};
const wallShape = new THREE.Shape();
const wallHeight = 10 / 2;
const wallWidth = 5 / 2;
wallShape.moveTo(0, 0);
wallShape.lineTo(wallHeight, 0);
wallShape.lineTo(wallHeight, wallWidth);
wallShape.lineTo(0, wallWidth);
const shape1Geometry = new THREE.ExtrudeBufferGeometry(
wallShape,
extrudeSettings
);
const material1 = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const mesh1 = new THREE.Mesh(shape1Geometry, material1);
scene.add(mesh1);
// Add shape 2
const rawPoints2 = [
{ x: -768.261181384325, y: -1452.8930274173617, z: 75.51 },
{ x: -767.7200012542307, y: -1453.9499824345112, z: 75.97 },
{ x: -762.5414672344923, y: -1456.9523466601968, z: 77.91 },
{ x: -756.644469935447, y: -1460.368300523609, z: 77.93 },
{ x: -754.4610880203545, y: -1461.6550271511078, z: 78.76 },
{ x: -746.576653342694, y: -1466.1585687585175, z: 81.47 },
];
const points2 = [];
rawPoints2.forEach((point) => {
points2.push(new THREE.Vector3(point.x + 800, point.z, point.y + 800));
});
const randomSpline2 = new THREE.CatmullRomCurve3(points2);
const extrudeSettings2 = {
steps: 30,
bevelEnabled: false,
extrudePath: randomSpline2,
};
const shape2Geometry = new THREE.ExtrudeBufferGeometry(
wallShape,
extrudeSettings2
);
const mesh2 = new THREE.Mesh(shape2Geometry, material1);
scene.add(mesh2);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(-1000, -1000, 10);
// scene.add( directionalLight );
const light = new THREE.HemisphereLight(0xffffbb, 0x080820, 1);
scene.add(light);
camera.position.set(-740.261181384325, 0, -1502.8930274173617, 85);
controls.update();
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
controls.update();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
Code reference
https://jsfiddle.net/vishalsdeshmukh/xduzrc3v/14/
I´ve been trying to enable tooltips on some imported 3D models, but it isnt working.
I already enabled tooltips in threbox, and I enabled tooltips in the options for the 3d element, as shown below.
tb = new Threebox(
map,
mbxContext,
{
realSunlight: true,
enableSelectingFeatures: true, //change this to false to disable fill-extrusion features selection
enableTooltips: true // change this to false to disable default tooltips on fill-extrusion and 3D models
}
);
var proptions = {
obj: './models/er.glb',
type: 'gltf',
scale: 10,
units: 'meters',
rotation: { x: 90, y: 0, z: 0 }, //default rotation
anchor: 'center',
adjustment: { x: 0, y: 0, z: 0.4 },
enableToltips: true
}
When i load the object i did the following:
tb.loadObj(proptions, function (model) {
model.setCoords(place);
model.addTooltip("A radar in the middle of nowhere", true);
model.setRotation({ x: 0, y: 0, z: Math.floor(Math.random() * 100) })
tb.add(model);
});
Although the object appears in the render, when I put the mouse above or i click it nothing shows the tooltip.
What am I missing ?
EDIT:
Following #jscastro response i changed the import in the top of my html page to <link href="./threebox-plugin/examples/css/threebox.css" rel="stylesheet" /> (the path is the correct to where the file is)
I also removed the enableTooltip: true in proptions.
Despite that it still does not work, Below i will leave the code as it is:
var origin = [-8.4, 41.20, 1];
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: origin,
zoom: 11,
pitch: 30,
antialias: true
});
//Things related to dateTime ommited
window.tb = new Threebox(
map,
map.getCanvas().getContext('webgl'),
{
realSunlight: true,
enableSelectingFeatures: true, //change this to false to disable fill-extrusion features selection
enableTooltips: true // change this to false to disable default tooltips on fill-extrusion and 3D models
}
);
map.on('style.load', async function () {
await importarLinhas();
// stats
// stats = new Stats();
// map.getContainer().appendChild(stats.dom);
animate();
map.addLayer({
id: 'custom_layer',
type: 'custom',
renderingMode: '3d',
onAdd: function (map, mbxContext) {
var eroptions = {
obj: './models/stationBus.fbx',
type: 'fbx',
scale: 0.01,
units: 'meters',
rotation: { x: 90, y: 20, z: 0 }, //default rotation
anchor: 'center',
adjustment: { x: -0.1, y: -0.1, z: 0.4 }
}
var poptions = {
obj: './models/Busstop.fbx',
type: 'fbx',
scale: 0.03,
units: 'meters',
rotation: { x: 90, y: 20, z: 0 }, //default rotation
anchor: 'center',
adjustment: { x: -0.1, y: -0.1, z: 0.1 }
}
var proptions = {
obj: './models/er.glb',
type: 'gltf',
scale: 2.7,
units: 'meters',
rotation: { x: 90, y: 0, z: 0 }, //default rotation
anchor: 'center',
adjustment: { x: 0, y: 0, z: 0.4 }
}
allNos.forEach((element) => { //For each one of a list that i fill first
//center of where the objects are
var place = [element.lng, element.lat, 0];
//cylinder as "base" for each one of the 3d Models
**//in here i cant do the Tooltip for the object**
const geometry = new THREE.CylinderGeometry(0.6, 0.6, 0.15, 32);
const material = new THREE.MeshLambertMaterial({ color: 0x5B5B5B });
const cylinder = new THREE.Mesh(geometry, material);
var baseOptions = {
obj: cylinder,
anchor: 'center',
adjustment: { x: 0, y: 0, z: -0.4 }
}
let base = tb.Object3D(baseOptions);
base.setCoords(place);
base.setRotation({ x: 90, y: 0, z: 0 })
//The text is just for the test
base.addTooltip("A radar in the middle of nowhere", true);
// base.castShadow = true;
window.tb.add(base);
//next i check what type of element it is
//it can only be one at the same time, so i use different models for each type
if (element.tipo === "p") {
window.tb.loadObj(poptions, function (model) {
model.setCoords(place);
model.addTooltip("A radar in the middle of nowhere", true);
model.setRotation({ x: 0, y: 0, z: Math.floor(Math.random() * 100) })
// model.castShadow = true;
window.tb.add(model);
});
}
if (element.tipo === "er") {
window.tb.loadObj(eroptions, function (model) {
model.setCoords(place);
model.addTooltip("A radar in the middle of nowhere", true);
model.setRotation({ x: 0, y: 0, z: Math.floor(Math.random() * 100) })
// model.castShadow = true;
window.tb.add(model);
});
}
if (element.tipo === "pr") {
window.tb.loadObj(proptions, function (model) {
model.setCoords(place);
model.addTooltip("A radar in the middle of nowhere", true);
model.setRotation({ x: 0, y: 0, z: Math.floor(Math.random() * 100) })
// model.castShadow = true;
window.tb.add(model);
});
}
});
},
render: function (gl, matrix) {
window.tb.setSunlight(date, origin.center);
window.tb.update();
}
})
map.addLayer(createCompositeLayer());
map.on('SelectedFeatureChange', onSelectedFeatureChange);
});
EDIT
I downloaded the page you shared in the chat, and I found many different issues and mistakes in your code.
1. You're using the wrong property to enable the selection of 3D objects, you use enableSelectingFeatures: true, //change this to false to disable fill-extrusion features selection, that is for Mapbox fill-extrusions features as said in the comment, but not for 3D models and objects, you have to use enableSelectingObjects: true. Only adding this, your problem with the tooltips on mouse over will be solved.
tb = new Threebox(
map,
mbxContext,
{
realSunlight: true,
enableSelectingObjects: true, //enable 3D models over/selection
enableTooltips: true // enable default tooltips on fill-extrusion and 3D models
}
);
But I have found other issues...
2. Your models scale initialization is too small, so you are hiding them below the big shapes you have created. The scale of your bus stop is scale: 0.01 and you define a place which is on the ground var place = [element.lng, element.lat, 0];, so it's hidden inside this CylinderGeometry
If you use scale: 1 you will see how your bus stops raises from the cylinder.
3. Same with the bus, you initialize them with scale: 1, which make them be hidden below the tubes and cylinders you have created. If you initialize them with scale: 10, and you elevate them 5 meters from the floor let truck = model.setCoords([lngB, latB, 4]); then you will see them raising.
4. Your models have a wrong initialization params mixing anchor and adjustment. anchor: center will center the pivotal center of your object properly, but then you apply negative values to x and y (which means decenter the object), and a z value that elevates the pivotal center adjustment: { x: -0.1, y: -0.1, z: 0.4 }. If you want your model on altitude use the 3rd coord in setCoords.
5. Your Cylinders and Tubes for the bus stops and bus lines are huge, and also they have the wrong init params, as you set them below the ground level -0.4 units adjustment: { x: 0, y: 0, z: -0.4 } (something supported by Mapbox but very bad resolved and producing weird effects. My recommendation would be to make them almost flat and at the ground level with no adjustment param. const geometry = new THREE.CylinderGeometry(0.6, 0.6, 0.01, 32);.
Summarizing, check all of these changes and let me know if it works.
How do I get the rotation of an element relative to the world coordination system?
I'm getting the information of an element by the following:
this.viewerComponent.viewer.impl.hitTest(event.layerX, event.layerY, false);
The result of this function is the following
{distance: 186476.22640731235, point: X.Vector3, face: X.Face3, faceIndex: 0, fragId: 372, …}
distance: 186476.22640731235
point: X.Vector3 {x: 70297.79662079967, y: 8922.73091035225, z: 9109.446866256267}
face: X.Face3 {a: 0, b: 1, c: 2, normal: X.Vector3, vertexNormals: Array(0), …}
faceIndex: 0
fragId: 372
dbId: 1959
object: X.Mesh
eulerOrder: (...)
useQuaternion: (...)
uuid: "A3D04442-BB20-4E0C-B371-3A987D212255"
name: ""
type: "Mesh"
parent: undefined
children: []
up: X.Vector3 {x: 0, y: 1, z: 0}
position: X.Vector3 {x: 0, y: 0, z: 0}
rotation: X.Euler {_x: 0, _y: 0, _z: 0, _order: "XYZ", onChangeCallback: ƒ}
quaternion: X.Quaternion {_x: 0, _y: 0, _z: 0, _w: 1, onChangeCallback: ƒ}
scale: X.Vector3 {x: 1, y: 1, z: 1}
rotationAutoUpdate: true
matrix: X.Matrix4
elements: Float32Array(16) [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
__proto__: Object
matrixWorld: X.Matrix4
elements: Float32Array(16) [10, 0, 0, 0, 0, 10, 0, 0, 0, 0, 10, 0, 79719.9609375, -6109.12646484375,
1962.4998779296875, 1]
__proto__: Object
matrixAutoUpdate: true
matrixWorldNeedsUpdate: false
visible: true
castShadow: false
receiveShadow: false
frustumCulled: true
renderOrder: 0
userData: {}
geometry: h {id: 2265, attributes: {…}, __webglInit: undefined, byteSize: 28, vb: Float32Array(6),
…}
material: X.LineBasicMaterial {uuid: "E36F7B3D-C885-475C-9AA6-A3D1024F7687", name: "", type:
"LineBasicMaterial", side: 0, opacity: 1, …}
isTemp: true
dbId: 529
modelId: 1
fragId: 2264
hide: false
isLine: true
isWideLine: false
isPoint: false
themingColor: undefined
id: 1
__proto__: X.Object3D
As seen, we have the information matrix (local coordination system which is connected to the element coordination system) and matrixWorld which should be the transformation matrix for element -> global coordination system. How do I now get the angles out of the matrixWorld to know what is the rotation by the elmenent in relation to the world coordination system.
Hope it is clear what i want, thank you in advance.
If I understand you correctly you may try:
//Getting fragment info by fragId if necessary
//const matrixWorld = new THREE.Matrix4();
//const fragProxy = NOP_VIEWER.impl.getFragmentProxy(NOP_VIEWER.model, fragId)
//fragProxy.getWorldMatrix(matrixWorld);
const position = new THREE.Vector3();
const quaternion = new THREE.Quaternion();
const scale = new THREE.Vector3();
matrixWorld.decompose( position, quaternion, scale );
See more on extracting rotation here
Thank you. It's a similar approach I've taken. Your solution would probably work, too.
public onMouseMove(event) {
var snapper = new
Autodesk.Viewing.Extensions.Snapping.Snapper(this.viewerComponent.viewer, {});
const hitTestResult = this.viewerComponent.viewer.impl.snappingHitTest(event.layerX,
event.layerY);
snapper.snapping3D(hitTestResult);
// Arrow
const geometry = new THREE.CylinderGeometry(1, 800, 2000, 100);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const mesh = new THREE.Mesh(geometry, material);
mesh.rotateZ(this.arcSinFunction(normal.x, normal.y, normal.z, 0, 1, 0)[0]);
mesh.name = 'section-mesh';
mesh.position.set(snapper.getSnapResult().intersectPoint.x,
snapper.getSnapResult().intersectPoint.y, snapper.getSnapResult().intersectPoint.z);
if (!this.viewerComponent.viewer.overlays.hasScene('section-scene')) {
this.viewerComponent.viewer.overlays.addScene('section-scene');
}
this.viewerComponent.viewer.overlays.addMesh([mesh, mesh_test], 'section-scene');
}
public arcSinFunction(n1: number, n2: number, n3: number, u1: number, u2: number,
u3:
number): Array<number> {
var zähler: number = Math.abs(n1 * u1 + n2 * u2 + n3 * u3);
// console.log(zähler);
var nenner: number = (Math.sqrt(n1 * n1 + n2 * n2 + n3 * n3)) * (Math.sqrt(u1 * u1 +
u2 * u2 + u3 * u3));
// console.log(nenner);
var resultRadian: number = Math.asin(zähler / nenner);
// console.log(resultRadian);
var pi = Math.PI;
var resultDegree = resultRadian * (180 / pi);
// console.log(resultDegree);
var res: Array<number> = [resultRadian, resultDegree];
// console.log(res);
return res;
}
Best regards
I was trying to get smooth effect while rotating or increasing in size a figure.
welcomeWrapper.addEventListener('mousedown', () => {
cube.scale.set(1.5, 1.5, 1.5);
TweenMax.to(cube.scale, 1, { ease: Power4.easeInOut });
});
//or
welcomeWrapper.addEventListener('mousemove', e => {
TweenLite.to(cube.scale, 1, {
css: {
x: e.movementX,
y: e.movementY,
z: e.movementX
}
});
cube.rotation.x += e.movementX / 250;
cube.rotation.y += e.movementY / 250;
cube.rotation.z += e.movementX / 250;
});
//tried this but it won't work
controls.enableDamping = true;
controls.minPolarAngle = 0.8;
controls.maxPolarAngle = 2.4;
controls.dampingFactor = 0.07;
controls.rotateSpeed = 0.07;
But every time I get:
Invalid property css set to {x: 0, y: 0, z: 0} Missing plugin? gsap.registerPlugin()
In order to scale the cube, for example to (2, 2, 2), you'll need to do something like this:
TweenMax.to(cube.scale, 1, { x: 2, y: 2, z: 2, ease: Power4.easeInOut });
There's no reason to use css:{} with a cube, since 3D objects in THREE.js don't follow CSS attributes.
I've created a group of cubes and I'm trying to figure out how to set the center so I can rotate them.
Here is the fiddle: https://jsfiddle.net/of1vfhzz/
Here I add the cubes:
side1 = new THREE.Object3D();
addCube({ name: 'side1topleft', x: -8.5, y: 7.5, z: 5 });
addCube({ name: 'side1topmiddle', x: -4, y: 7.5, z: 5 });
addCube({ name: 'side1topright', x: .5, y: 7.5, z: 5 });
addCube({ name: 'side1middleleft', x: -8.5, y: 3, z: 5 });
addCube({ name: 'side1middlemiddle', x: -4, y: 3, z: 5 });
addCube({ name: 'side1middleright', x: .5, y: 3, z: 5 });
addCube({ name: 'side1bottomleft', x: -8.5, y: -1.5, z: 5 });
addCube({ name: 'side1bottommiddle', x: -4, y: -1.5, z: 5 });
addCube({ name: 'side1bottomright', x: .5, y: -1.5, z: 5 });
scene.add(side1);
function addCube(data) {
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.position.x = data.x
cube.position.y = data.y
cube.position.z = data.z
cube.rotation.set(0, 0, 0);
cube.name = data.name;
side1.add(cube);
}
Then in render scene I rotate it around the y-axis, but I need to set the center. I tried translate, but I'm not getting it.
You want your group of meshes to rotate around the group center.
One option is to translate your mesh geometries so, as a collection, they are centered around the local origin.
If you don't want to do that, then you can create a grand-parent object pivot, and rotate that.
In your case, side1 is the parent of your child meshes. So use this pattern:
var pivot = new THREE.Group();
scene.add( pivot );
pivot.add( side1 );
side1.position.set( 4, - 3, - 5 ); // the negative of the group's center
In your animation loop, rotate the pivot;
pivot.rotation.z += 0.02;
fiddle: https://jsfiddle.net/of1vfhzz/1/
three.js r.77