Extrude 3d shape from THREE.Line object in three.js - javascript

In three.js I have created an ellipseCurve for which I want to extrude and make 3d.
CODE USE TO MAKE THIS:
var curve = new THREE.EllipseCurve(
0, 0, // ax, aY
10, 13.3, // xRadius, yRadius
0, 2 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0 // aRotation
);
var path = new THREE.Path( curve.getPoints( 100 ) );
var geometrycirc = path.createPointsGeometry( 50 );
var materialcirc = new THREE.LineBasicMaterial( {
color : 0xff0000
} );
// Create the final object to add to the scene
var ellipse = new THREE.Line( geometrycirc, materialcirc );
this.scene.add( ellipse );
I want to use this ellipseCurve as a basis to create an extruded shape similar to these examples.
https://threejs.org/examples/#webgl_geometry_extrude_splines
These examples seem to use vectors to do this, so I assume I need to convert the curve into one.
I am not sure how to do this since I have been unable to find references on this matter.
Any help to do this?
UPDATE: 22/03/2017
Right so I tried to implement the same method of extrusion as found on:
https://threejs.org/examples/#webgl_geometry_extrude_splines
I was able to but this spline into my scene:
HERE IS THE CODE TO DO THIS:
/////////////////////////////////////////////////////////////////////////
// My line curve //
/////////////////////////////////////////////////////////////////////////
var curve = new THREE.EllipseCurve(
0, 0, // ax, aY
10, 13.3, // xRadius, yRadius
0, 2 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0 // aRotation
);
var path = new THREE.Path( curve.getPoints( 100 ) );
var geometrycirc = path.createPointsGeometry( 50 );
var materialcirc = new THREE.LineBasicMaterial( {
color : 0xff0000
} );
// Create the final object based on points and material
var ellipse = new THREE.Line( geometrycirc, materialcirc );
this.scene.add( ellipse );
////////////////////////////////////////////////////////////////////////
// Example of sample closed spine //
////////////////////////////////////////////////////////////////////////
var sampleClosedSpline = new THREE.CatmullRomCurve3( [
new THREE.Vector3( 0, -40, -40 ),
new THREE.Vector3( 0, 40, -40 ),
new THREE.Vector3( 0, 140, -40 ),
new THREE.Vector3( 0, 40, 40 ),
new THREE.Vector3( 0, -40, 40 )
] );
sampleClosedSpline.type = 'catmullrom';
sampleClosedSpline.closed = true;
//////////////////////////////////////////////////////////////////////////////
// Extrusion method to covert the spline/vector data into 3d object //
//////////////////////////////////////////////////////////////////////////////
// I used this method and have tried the following properties but these do not work
//
// var tube = new THREE.TubeBufferGeometry( curve, 12, 2, 20, true);
//
// 1. ellipse.clone()
// 2. geometrycirc.clone()
// 3. materialcirc.clone()
// 4. path.clone()
// 5. curve
//
// Therefore I am either doing something wrong or there must be a further process that needs
// to be implemented.
// this works as standard
var tube = new THREE.TubeBufferGeometry( sampleClosedSpline, 12, 2, 20, true);
var tubeMesh = THREE.SceneUtils.createMultiMaterialObject( tube, [
new THREE.MeshLambertMaterial( {
color: 0xffffff
} ),
new THREE.MeshBasicMaterial( {
color: 0xff00ff,
opacity: 0.3,
wireframe: true,
transparent: true
} ) ] );
tubeMesh.scale.set( .2, .2, .2 );
this.scene.add( tubeMesh );
///////////////////////////////////////////////////////////////////////////////
So when I place the spline property for the one that I have created i get a black screen and the following error msgs:
var curve;
and the other variables used (refer to code to see what I have tried)
EDIT: 23/03/2017
WestLangley's method was the ideal solution

You want to create a TubeGeometry or TubeBufferGeometry in the shape of an ellipse.
Here is one way to do it that is general enough for others to use, too.
First, create a new class that defines your path:
// Ellipse class, which extends the virtual base class Curve
class Ellipse extends THREE.Curve {
constructor( xRadius, yRadius ) {
super();
// add radius as a property
this.xRadius = xRadius;
this.yRadius = yRadius;
}
getPoint( t, optionalTarget = new THREE.Vector3() ) {
const point = optionalTarget;
var radians = 2 * Math.PI * t;
return new THREE.Vector3( this.xRadius * Math.cos( radians ),
this.yRadius * Math.sin( radians ),
0 );
}
}
Then create the geometry from the path.
// path
var path = new Ellipse( 5, 10 );
// params
var pathSegments = 64;
var tubeRadius = 0.5;
var radiusSegments = 16;
var closed = true;
var geometry = new THREE.TubeBufferGeometry( path, pathSegments, tubeRadius, radiusSegments, closed );
Super easy. :)
Fiddle: http://jsfiddle.net/62qhxags/
three.js r.129

Related

ThreeJS: applying edge geometry to ArrowHelper

I'm trying to create an arrow using ArrowHelper in ThreeJS:
let arrow = new THREE.ArrowHelper(direction.normalize(), new THREE.Vector3(), length, color, headLength, headWidth);
Also I want to use a separate color for edges. I realize that I need to use THREE.EdgesGeometry, but how to apply it I don't quite understand. Could anybody help me?
Update
sorry for confusion, I thought the arrow uses pyramid, not cone. Is there a way to replace cone with pyramid and use different color for edges?
Update
Thank you all for your answers, they were really helpful. I ended up with creating custom arrow class (copied most of the code from ArrowHelper):
class CustomArrow extends THREE.Object3D {
constructor( dir, origin, length, color, edgeColor, headLength, headWidth ) {
super();
// dir is assumed to be normalized
this.type = 'CustomArrow';
if ( dir === undefined ) dir = new THREE.Vector3( 0, 0, 1 );
if ( origin === undefined ) origin = new THREE.Vector3( 0, 0, 0 );
if ( length === undefined ) length = 1;
if ( color === undefined ) color = 0xffff00;
if ( headLength === undefined ) headLength = 0.2 * length;
if ( headWidth === undefined ) headWidth = 0.2 * headLength;
if ( this._lineGeometry === undefined ) {
this._lineGeometry = new THREE.BufferGeometry();
this._lineGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
this._coneGeometry = new THREE.ConeBufferGeometry( 0.5, 1, 6);
this._coneGeometry.translate( 0, - 0.5, 0 );
this._axis = new THREE.Vector3();
}
this.position.copy( origin );
this.line = new THREE.Line( this._lineGeometry, new THREE.LineBasicMaterial( { color: color, toneMapped: false, linewidth: 4 } ) );
this.line.matrixAutoUpdate = false;
this.add( this.line )
// base material
this.cone = new THREE.Mesh( this._coneGeometry, new THREE.MeshBasicMaterial( { color: color, toneMapped: false } ) );
this.add(this.cone);
// wire frame
this.wireframe = new THREE.Mesh( this._coneGeometry, new THREE.MeshBasicMaterial( {
color: edgeColor,
toneMapped: false,
wireframe: true,
wireframeLinewidth: 2 } ) );
this.add(this.wireframe);
this.setDirection( dir );
this.setLength( length, headLength, headWidth );
}
setDirection( dir ) {
// dir is assumed to be normalized
if ( dir.y > 0.99999 ) {
this.quaternion.set( 0, 0, 0, 1 );
} else if ( dir.y < - 0.99999 ) {
this.quaternion.set( 1, 0, 0, 0 );
} else {
this._axis.set( dir.z, 0, - dir.x ).normalize();
const radians = Math.acos( dir.y );
this.quaternion.setFromAxisAngle( this._axis, radians );
}
}
setLength( length, headLength, headWidth ) {
if ( headLength === undefined ) headLength = 0.2 * length;
if ( headWidth === undefined ) headWidth = 0.2 * headLength;
this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
this.line.updateMatrix();
this.cone.scale.set( headWidth, headLength, headWidth );
this.cone.position.y = length;
this.cone.updateMatrix();
this.wireframe.scale.set( headWidth, headLength, headWidth );
this.wireframe.position.y = length;
this.wireframe.updateMatrix();
}
setColor( color ) {
this.line.material.color.set( color );
// this.cone.material.color.set( color );
// this.wireframe.material.color.set( color );
}
copy( source ) {
super.copy( source, false );
this.line.copy( source.line );
this.cone.copy( source.cone );
this.wireframe.copy( source.wireframe );
return this;
}
}
For some reason linewidth and wireframeLinewidth don't affect lines widths. Any idea why?
edit: A pyramid is a cone with 4 radial segments, if you want that, look at how the arrowhelper constructs it's cone (which is with a tapered CylinderGeometry) and line based on the parameters and replace it with a cone geometry constructed as follows:
original:
_coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
new:
_coneGeometry = new ConeBufferGeometry( 0.5, 1, 4);
Then you don't have to use the EdgesGeometry, but use the wireframe material option (per #prisoner849's comment):
let wireframeMaterial = new THREE.MeshBasicMaterial({color: "aqua", wireframe: true});
let coneEdgeMesh = new THREE.Mesh(_coneGeometry, wireframeMaterial);
Original answer:
THREE.ArrowHelper consists of 2 Object3Ds: one THREE.Line for the line and one THREE.Mesh for the cone of the arrow. The Line geometry only consists of 2 points and has no edges because it is a line, but for the cone you can use:
let coneEdgeGeometry = new THREE.EdgesGeometry(arrow.cone.geometry);
Then you construct a LineSegments object with the edge geometry and the color you want:
let line = new THREE.LineSegments( coneEdgeGeometry, new THREE.LineBasicMaterial( { color: 0xffffff } ) );
arrow.add(line);
If the cone edge is not showing, try setting the renderOrder of the THREE.LineSegments to -1 (this might give other issues)
You can change the colour of arrow's cone like this:
body {
overflow: hidden;
margin: 0;
}
<script type="module">
import * as THREE from "https://threejs.org/build/three.module.js";
import {OrbitControls} from "https://threejs.org/examples/jsm/controls/OrbitControls.js";
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight,
1, 100);
camera.position.set(0, 5, 10);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
new OrbitControls(camera, renderer.domElement);
scene.add(new THREE.GridHelper());
// different colors
let ah = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(-4, 0, 0),
5,
"magenta" /* default colour */);
ah.cone.material.color.set("red"); // change color of cone
scene.add(ah);
// colourful pyramid
let cg = new THREE.SphereBufferGeometry(0.5, 4, 2).toNonIndexed();
let pos = cg.attributes.position;
for (let i = 0; i < pos.count; i++){
if (pos.getY(i) < 0) pos.setY(i, 0);
}
console.log(cg);
let cls = [
new THREE.Color("red"),
new THREE.Color("green"),
new THREE.Color("blue"),
new THREE.Color("yellow")
]
let colors = [];
for(let i = 0; i < 2; i++){
cls.forEach( (c) => {
colors.push(c.r, c.g, c.b);
colors.push(c.r, c.g, c.b);
colors.push(c.r, c.g, c.b);
});
}
cg.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
let cm = new THREE.MeshBasicMaterial({vertexColors: true});
let co = new THREE.Mesh(cg, cm);
co.scale.set(1, 5, 1);
scene.add(co);
renderer.setAnimationLoop(()=>{
renderer.render(scene, camera);
});
</script>

Updating DecalGeometry vertices, UVs,

I am currently playing with ThreeJS decals. I have been able to put a beautiful stain on my sphere.
Here is the piece of code I use to "apply" the decal on my sphere. (I have some custom classes, but don't worry about this.
// Create sphere
var mainMesh = new THREE.Mesh(
new THREE.SphereGeometry(7, 16, 16),
new THREE.MeshBasicMaterial({ color: 0x00a1fd })
);
// Declare decal material
var decalMaterial = new THREE.MeshPhongMaterial({
color : 0xff0000,
specular : 0x444444,
map : TextureLoader.instance.getTexture('http://threejs.org/examples/textures/decal/decal-diffuse.png'),
normalMap : TextureLoader.instance.getTexture('http://threejs.org/examples/textures/decal/decal-normal.jpg'),
normalScale : new THREE.Vector2( 1, 1 ),
shininess : 30,
transparent : true,
depthTest : true,
depthWrite : false,
polygonOffset : true,
polygonOffsetFactor : -4,
wireframe : false
});
// Create decal itself
var decal = new THREE.Mesh(
new THREE.DecalGeometry(
mainMesh,
new THREE.Vector3(0, 2.5, 3),
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(8, 8, 8),
new THREE.Vector3(1, 1, 1)
),
decalMaterial.clone()
);
// Add mesh + decal + helpers
scene.add(
mainMesh,
new THREE.HemisphereLight(0xffffff, 0, 1),
decal,
new THREE.WireframeHelper(decal, 0xffff00)
);
decal.add(new THREE.BoxHelper(decal, 0xffff00));
Now, I woud like to move this stain on my sphere, and thus, update the geometry of my decal.
Unfortunately, when I call decal.geometry.computeDecal(), the mesh of the decal does not update. I can't find any solution about this.
function moveDecal()
{
decal.translateX(1);
decal.geometry.computeDecal();
};
According to the DecalGeometry class, the function computeDecal already set to true various members required to update vertices, colors, UVs, ....
this.computeDecal = function() {
// [...]
this.verticesNeedUpdate = true;
this.elementsNeedUpdate = true;
this.morphTargetsNeedUpdate = true;
this.uvsNeedUpdate = true;
this.normalsNeedUpdate = true;
this.colorsNeedUpdate = true;
};
Thank you for your help ! :D
PS : ThreeJS r80
You are trying to update vertices of your geometry.
You can change the value of a vertex componnent,
geometry.vertices[ 0 ].x += 1;
but you can't add new veritices
geometry.vertices.push( new THREE.Vector3( x, y, z ) ); // not allowed
or assign a new vertex array
geometry.vertices = new_array; // not allowed
after the geometry has been rendered at least once.
Similalry, for other attributes, such as UVs.
For more info, see this answer: verticesNeedUpdate in Three.js.
three.js r.80

BoxGeometry not aligning with SphereGeometry properly

I am trying to create spikes on earth(sphere geometry). Though everything works fines, but spikes dont align with globe. I want spike to align something like below image. But my spikes dont lookAt(new THREE.Vector3(0,0,0)) despite mentioned. Please help me out.
I purposefully mentioned code required for debugging. Let me know if you need more code for this. Below image is how i want my spikes to align with sphere.
But this is how it looks
My Main JS initialization file.
$(document).ready(function () {
// Initializing Camera
Influx.Camera = new Influx.Camera({
fov: 60,
aspectRatio: window.innerWidth / window.innerHeight,
near: 1,
far: 1000,
position: {
x: 0,
y: 0,
z: 750
}
});
//Initializing Scene
Influx.Scene = new Influx.Scene();
// Initializing renderer
Influx.Renderer = new Influx.Renderer({
clearColor: 0x000000,
size: {
width: window.innerWidth,
height: window.innerHeight
}
});
Influx.Globe = new Influx.Globe({
radius: 300,
width: 50,
height: 50
});
//
Influx.Stars = new Influx.Stars({
particleCount: 15000,
particle: {
color: 0xFFFFFF,
size: 1
}
});
Influx.moveTracker = new Influx.moveTracker();
Influx.EventListener = new Influx.EventListener();
(function animate() {
requestAnimationFrame( animate );
render();
controls.update();
})();
function render() {
camera.lookAt(scene.position);
group.rotation.y -= 0.001;
renderer.render( scene, camera );
};
});
Below is code responsible for generating spikes on Globe.
Influx.Spikes = function (lat, long) {
// convert the positions from a lat, lon to a position on a sphere.
var latLongToVector3 = function(lat, lon, RADIUS, heigth) {
var phi = (lat) * Math.PI/180,
theta = (lon-180) * Math.PI/180;
var x = -(RADIUS+heigth) * Math.cos(phi) * Math.cos(theta),
y = (RADIUS+heigth) * Math.sin(phi),
z = (RADIUS+heigth) * Math.cos(phi) * Math.sin(theta);
return new THREE.Vector3(x, y, z);
};
var geom = new THREE.Geometry();
var BoxGeometry = new THREE.BoxGeometry(1, 100, 1);
//iterates through the data points and makes boxes with the coordinates
var position = latLongToVector3(lat, long, 300, 2);
var box = new THREE.Mesh( BoxGeometry );
//each position axis needs to be set separately, otherwise the box
//will instantiate at (0,0,0)
box.position.x = position.x;
box.position.y = position.y;
box.position.z = position.z;
box.lookAt(new THREE.Vector3(0, 0, 0));
box.updateMatrix();
//merges the geometry to speed up rendering time, don't use THREE.GeometryUtils.merge because it's deprecated
geom.merge(box.geometry, box.matrix);
var total = new THREE.Mesh(geom, new THREE.MeshBasicMaterial({
color: getRandomColor(),
morphTargets: true
}));
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
//add boxes to the group
group.add(total);
scene.add(group);
};
Influx.Camera = function(params = {}) {
if ( !$.isEmptyObject(params) ) {
window.camera = new THREE.PerspectiveCamera(params.fov, params.aspectRatio, params.near, params.far);
camera.position.set(params.position.x, params.position.y, params.position.z);
camera.lookAt(new THREE.Vector3(0,0,0));
} else {
console.log("Trouble with Initializing Camera");
return;
}
};
Remember that lookAt takes a direction vector, you give to this method the vector (0, 0, 0), this is actually not a normalized direction vector. So you must calculate the direction:
from your box position to the center of the sphere AND normalize it.
var dir = box.position.sub(world.position).normalize();
box.lookAt(dir);
And now just a set of code good conventions that may help you:
var BoxGeometry = new THREE.BoxGeometry(1, 100, 1);
Here I would rather use another var name for the box geometry, not to mix up with the "class" definition from THREE and to follow naming conventions:
var boxGeometry = new THREE.BoxGeometry(1, 100, 1);
And here:
box.position.x = position.x;
box.position.y = position.y;
box.position.z = position.z;
You can just set:
box.position.copy(position);
I also meet this problem, and I fixed it, the solution is: box.lookAt(new THREE.Vector3(0, 0, 0)) must after box.scale.z = xxxx

Draw a circle (not shaded) with Three.js

I am trying to draw a circle very similar to the orbital patterns on this website. I would like to use Three.js instead of pure WebGL.
Three.js r50 added CircleGeometry. It can be seen (albeit with a face) in the WebGL Geometries example.
The first vertex in the geometry is created at the center of the circle (in r84, see CircleGeometry.js line 71, in r65, see CircleGeometry.js line 18), which is nifty if you are going for that "full Pac-Man" or "uninformative pie chart" look. Oh, and it appears to be necessary if you are going to use any material aside from LineBasicMaterial / LineDashedMaterial.
I've verified that the following code works in both r60 & r65:
var radius = 100,
segments = 64,
material = new THREE.LineBasicMaterial( { color: 0x0000ff } ),
geometry = new THREE.CircleGeometry( radius, segments );
// Remove center vertex
geometry.vertices.shift();
// Non closed circle with one open segment:
scene.add( new THREE.Line( geometry, material ) );
// To get a closed circle use LineLoop instead (see also #jackrugile his comment):
scene.add( new THREE.LineLoop( geometry, material ) );
PS: The "docs" now include a nice CircleGeometry interactive example: https://threejs.org/docs/#api/geometries/CircleGeometry
The API changed slightly in newer versions of threejs.
var segmentCount = 32,
radius = 100,
geometry = new THREE.Geometry(),
material = new THREE.LineBasicMaterial({ color: 0xFFFFFF });
for (var i = 0; i <= segmentCount; i++) {
var theta = (i / segmentCount) * Math.PI * 2;
geometry.vertices.push(
new THREE.Vector3(
Math.cos(theta) * radius,
Math.sin(theta) * radius,
0));
}
scene.add(new THREE.Line(geometry, material));
Modify segmentCount to make the circle smoother or more jagged as needed by your scene. 32 segments will be quite smooth for small circles. For orbits such as those on the site you link you, you may want to have a few hundred.
Modify the order of the three components within the Vector3 constructor to choose the orientation of the circle. As given here, the circle will be aligned to the x/y plane.
I used code that Mr.doob references in this github post.
var resolution = 100;
var amplitude = 100;
var size = 360 / resolution;
var geometry = new THREE.Geometry();
var material = new THREE.LineBasicMaterial( { color: 0xFFFFFF, opacity: 1.0} );
for(var i = 0; i <= resolution; i++) {
var segment = ( i * size ) * Math.PI / 180;
geometry.vertices.push( new THREE.Vertex( new THREE.Vector3( Math.cos( segment ) * amplitude, 0, Math.sin( segment ) * amplitude ) ) );
}
var line = new THREE.Line( geometry, material );
scene.add(line);
This example is in the Three.js documentation:
var material = new THREE.MeshBasicMaterial({
color: 0x0000ff
});
var radius = 5;
var segments = 32; //<-- Increase or decrease for more resolution I guess
var circleGeometry = new THREE.CircleGeometry( radius, segments );
var circle = new THREE.Mesh( circleGeometry, material );
scene.add( circle );
I had to do this lol:
function createCircle() {
let circleGeometry = new THREE.CircleGeometry(1.0, 30.0);
circleGeometry.vertices.splice(0, 1); //<= This.
return new THREE.LineLoop(circleGeometry,
new THREE.LineBasicMaterial({ color: 'blue' }));
}
let circle = createCircle();
Reason: Otherwise, it doesn't draw a "pure" circle, there's a line coming from the center to the rim of the circle, even if you use LineLoop instead of Line. Splicing (removing) the first vertex from the array is a hack but seems to do the trick. :)
(Note that apparently, according to mrienstra's answer, "Oh, and it appears to be necessary if you are going to use any material aside from LineBasicMaterial / LineDashedMaterial.")
If you want thickness, though, you're screwed ("Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.")... Unless you use: https://github.com/spite/THREE.MeshLine
Code example for that is here: https://stackoverflow.com/a/61312721/1599699
Well, I dunno when they added it - but TorusGeometry should do the job...
THREE TorusGeometry
const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const torus = new THREE.Mesh( geometry, material );
scene.add( torus );
Dunno, but I think it shouldn't be (much) more expensive than the line thingy and it's a buffer geometry and you may adjust size and material etc...
See the three.js sample http://mrdoob.github.com/three.js/examples/webgl_lines_colors.html to see how to draw colored lines.
A circle like the ones you cite is drawn as a large # of little straight segments. (Actually, the ones you show may be ellipses)
var getStuffDashCircle2 = function () {
var segment = 100, radius = 100;
var lineGeometry = new THREE.Geometry();
var vertArray = lineGeometry.vertices;
var angle = 2 * Math.PI / segment;
for (var i = 0; i < segment; i++) {
var x = radius * Math.cos(angle * i);
var y = radius * Math.sin(angle * i);
vertArray.push(new THREE.Vector3(x, y, 0));
}
lineGeometry.computeLineDistances();
var lineMaterial = new THREE.LineDashedMaterial({ color: 0x00cc00, dashSize: 4, gapSize: 2 });
var circle = new THREE.Line(lineGeometry, lineMaterial);
circle.rotation.x = Math.PI / 2;
circle.position.y = cylinderParam.trackHeight+20;
return circle;
}
I had some issues getting the other answers to work here -- in particular, CircleGeometry had an extra point at the center of the circle, and I didn't like the hack of trying to remove that vertex.
EllipseCurve does what I wanted (verified in r135):
const curve = new THREE.EllipseCurve(
0.0, 0.0, // Center x, y
10.0, 10.0, // x radius, y radius
0.0, 2.0 * Math.PI, // Start angle, stop angle
);
const pts = curve.getSpacedPoints(256);
const geo = new THREE.BufferGeometry().setFromPoints(pts);
const mat = new THREE.LineBasicMaterial({ color: 0xFF00FF });
const circle = new THREE.LineLoop(geo, mat);
scene.add(circle);

How to rotate a object on axis world three.js?

Is it possible to do rotations taking axis of the world and not of the object?
I need to do some rotations of an object, but after the first rotation, I can't do other rotations like i want.
If it's not possible to do rotation on the axis of the world, my second option is to reset the axis after the first rotation. Is there some function for this?
I can't use object.eulerOrder because it changes the orientation of my object when I set object.eulerOrder="YZX" after some rotations.
UPDATED: THREE - 0.125.2
DEMO: codesandbox.io
const THREE = require("three");
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(1, 1, 1, 4, 4, 4);
const material = new THREE.MeshBasicMaterial({
color: 0x628297,
wireframe: true
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// select the Z world axis
const myAxis = new THREE.Vector3(0, 0, 1);
// rotate the mesh 45 on this axis
cube.rotateOnWorldAxis(myAxis, THREE.Math.degToRad(45));
function animate() {
// rotate our object on its Y axis,
// but notice the cube has been transformed on world axis, so it will be tilted 45deg.
cube.rotation.y += 0.008;
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
Here's a small variation. Tested with r56.
THREE.Object3D._matrixAux = new THREE.Matrix4(); // global auxiliar variable
// Warnings: 1) axis is assumed to be normalized.
// 2) matrix must be updated. If not, call object.updateMatrix() first
// 3) this assumes we are not using quaternions
THREE.Object3D.prototype.rotateAroundWorldAxis = function(axis, radians) {
THREE.Object3D._matrixAux.makeRotationAxis(axis, radians);
this.matrix.multiplyMatrices(THREE.Object3D._matrixAux,this.matrix); // r56
THREE.Object3D._matrixAux.extractRotation(this.matrix);
this.rotation.setEulerFromRotationMatrix(THREE.Object3D._matrixAux, this.eulerOrder );
this.position.getPositionFromMatrix( this.matrix );
}
THREE.Object3D.prototype.rotateAroundWorldAxisX = function(radians) {
this._vector.set(1,0,0);
this.rotateAroundWorldAxis(this._vector,radians);
}
THREE.Object3D.prototype.rotateAroundWorldAxisY = function(radians) {
this._vector.set(0,1,0);
this.rotateAroundWorldAxis(this._vector,radians);
}
THREE.Object3D.prototype. rotateAroundWorldAxisZ = function(degrees){
this._vector.set(0,0,1);
this.rotateAroundWorldAxis(this._vector,degrees);
}
The three last lines are just to resync the params (position,rotation) from the matrix... I wonder if there is a more efficient way to do that...
Somewhere around r59 this gets a lot easier (rotate around x):
bb.GraphicsEngine.prototype.calcRotation = function ( obj, rotationX)
{
var euler = new THREE.Euler( rotationX, 0, 0, 'XYZ' );
obj.position.applyEuler(euler);
}
Updated answer from #Neil (tested on r98)
function rotateAroundWorldAxis(obj, axis, radians) {
let rotWorldMatrix = new THREE.Matrix4();
rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);
rotWorldMatrix.multiply(obj.matrix);
obj.matrix = rotWorldMatrix;
obj.setRotationFromMatrix(obj.matrix);
}
#acarlon Your answer might just have ended a week of frustration. I've refined your function a bit. Here are my variations. I hope this saves someone else the 20+ hours I spent trying to figure this out.
function calcRotationAroundAxis( obj3D, axis, angle ){
var euler;
if ( axis === "x" ){
euler = new THREE.Euler( angle, 0, 0, 'XYZ' );
}
if ( axis === "y" ){
euler = new THREE.Euler( 0, angle, 0, 'XYZ' );
}
if ( axis === "z" ){
euler = new THREE.Euler( 0, 0, angle, 'XYZ' );
}
obj3D.position.applyEuler( euler );
}
function calcRotationIn3D( obj3D, angles, order = 'XYZ' ){
var euler;
euler = new THREE.Euler( angles.x, angles.y, angles.z, order );
obj3D.position.applyEuler( euler );
}
This works beautifully in r91.
Hope it helps.

Categories

Resources