I am trying to animate a cube along a path in three.js.
CODE
// Ellipse class, which extends the virtual base class Curve
var curve = new THREE.EllipseCurve(
0, 0, // ax, aY
16, 21.28, // xRadius, yRadius
0, 2 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0 // aRotation
);
//defines the amount of points the path will have
var path = new THREE.Path( curve.getPoints( 100 ) );
var geometrycirc = path.createPointsGeometry( 100 );
var materialcirc = new THREE.LineBasicMaterial( {
color : 0xff0000
} );
// Create the final object to add to the scene
var ellipse = new THREE.Line( geometrycirc, materialcirc );
ellipse.position.set(0,1,0);
this.scene.add( ellipse );
// add the box to the scene
this.scene.add(this.box);
I have being doing some research into how this could be done and came across this fiddle animate on path This method uses a the THREE.SplineCurve3 method to create the points for the box to use.
My question is do I need to convert my path to use the THREE.SplineCurve3 method.
Or can I use the path as it is?
Any help or pointers would be appreciated.
many thanks
Object Animating on path
Code
// GLOBALS - ALLOCATE THESE OUTSIDE OF THE RENDER LOOP - CHANGED
var cubes = [], marker, spline;
var matrix = new THREE.Matrix4();
var up = new THREE.Vector3( 0, 1, 0 );
var axis = new THREE.Vector3( );
var pt, radians, axis, tangent, path;
// the getPoint starting variable - !important - You get me ;)
var t = 0;
//This function generates the cube and chooses a random color for it
//on initial load.
function getCube(){
// cube mats and cube
var mats = [];
for (var i = 0; i < 6; i ++) {
mats.push(new
THREE.MeshBasicMaterial({color:Math.random()*0xffffff}));
}
var cube = new THREE.Mesh(
new THREE.CubeGeometry(2, 2, 2),
new THREE.MeshFaceMaterial( mats )
);
return cube
}
// Ellipse class, which extends the virtual base class Curve
function Ellipse( xRadius, yRadius ) {
THREE.Curve.call( this );
// add radius as a property
this.xRadius = xRadius;
this.yRadius = yRadius;
}
Ellipse.prototype = Object.create( THREE.Curve.prototype );
Ellipse.prototype.constructor = Ellipse;
// define the getPoint function for the subClass
Ellipse.prototype.getPoint = function ( t ) {
var radians = 2 * Math.PI * t;
return new THREE.Vector3( this.xRadius * Math.cos( radians ),
this.yRadius * Math.sin( radians ),
0 );
};
//
var mesh, renderer, scene, camera, controls;
function init() {
// renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 20, 20, 20 );
// controls
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.addEventListener( 'change', render ); // use if there is no animation loop
controls.minDistance = 10;
controls.maxDistance = 50;
// light
var light = new THREE.PointLight( 0xffffff, 0.7 );
camera.add( light );
scene.add( camera ); // add to scene only because the camera has a child
// axes
scene.add( new THREE.AxisHelper( 20 ) );
////////////////////////////////////////
// Create the cube //
////////////////////////////////////////
marker = getCube();
marker.position.set(0,0,0);
scene.add(marker);
////////////////////////////////////////
// Create an Extruded shape //
////////////////////////////////////////
// path
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 );
// material
var material = new THREE.MeshPhongMaterial( {
color: 0x0080ff,
} );
// mesh
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
//////////////////////////////////////////////////////////////////////////
// Create the path which is based on our shape above //
//////////////////////////////////////////////////////////////////////////
//Please note that this red ellipse was only created has a guide so that I could be certain that the square is true to the tangent and positioning.
// Ellipse class, which extends the virtual base class Curve
var curve = new THREE.EllipseCurve(
0, 0, // ax, aY
6, 11, // xRadius, yRadius
0, 2 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0 // aRotation
);
//defines the amount of points the path will have
var path2 = new THREE.Path( curve.getPoints( 100 ) );
geometrycirc = path2.createPointsGeometry( 100 );
var materialcirc = new THREE.LineBasicMaterial( {
color : 0xff0000
} );
// Create the final object to add to the scene
var ellipse = new THREE.Line( geometrycirc, materialcirc );
ellipse.position.set(0,0,0);
scene.add( ellipse );
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
// set the marker position
pt = path.getPoint( t );
// set the marker position
marker.position.set( pt.x, pt.y, pt.z );
// get the tangent to the curve
tangent = path.getTangent( t ).normalize();
// calculate the axis to rotate around
axis.crossVectors( up, tangent ).normalize();
// calcluate the angle between the up vector and the tangent
radians = Math.acos( up.dot( tangent ) );
// set the quaternion
marker.quaternion.setFromAxisAngle( axis, radians );
t = (t >= 1) ? 0 : t += 0.002;
renderer.render( scene, camera );
}
init();
animate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/82/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
Conclusion
So I was very Fortunate to stumble upon the answer.
In my case it was the creation of a subclass to my object which allowed me to use it's data as points so that an object could use it as a guide.
Yes I am aware that you are thinking 'What is this guy talking about' so I have created a fiddle for you to look at and study.
Fiddle: Object Animating on path
Related
For a web project, I would like to draw random points with Three.js.
This is my code so far:
<script type="module">
import * as THREE from 'https://threejs.org/build/three.module.js';
import { TrackballControls } from 'https://threejs.org/examples/jsm/controls/TrackballControls.js';
let camera, scene, renderer, controls;
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xffffff );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 0, 0, 500 );
controls = new TrackballControls( camera, renderer.domElement );
controls.minDistance = 200;
controls.maxDistance = 500;
scene.add( new THREE.AmbientLight( 0x222222 ) );
const light = new THREE.PointLight( 0xffffff );
light.position.copy( camera.position );
scene.add( light );
//
//
const randomPoints = [];
for ( let i = 0; i < 10; i ++ ) {
randomPoints.push( new THREE.Vector3( ( i - 4.5 ) * 50, THREE.MathUtils.randFloat( - 50, 50 ), THREE.MathUtils.randFloat( - 50, 50 ) ) );
}
const randomSpline = new THREE.CatmullRomCurve3( randomPoints );
//
const extrudeSettings2 = {
steps: 120,
bevelEnabled: false,
extrudePath: randomSpline
};
const pts2 = [], numPts = 5;
for ( let i = 0; i < numPts * 2; i ++ ) {
const l = i % 2 == 1 ? 10 : 10;
const a = i / numPts * Math.PI;
pts2.push( new THREE.Vector2( Math.cos( a ) * l, Math.sin( a ) * l ) );
}
const shape2 = new THREE.Shape( pts2 );
const geometry2 = new THREE.ExtrudeGeometry( shape2, extrudeSettings2 );
const material2 = new THREE.MeshLambertMaterial( { color: 0xff8000, wireframe: false } );
const mesh2 = new THREE.Mesh( geometry2, material2 );
scene.add( mesh2 );
//
const materials = [ material2 ];
const extrudeSettings3 = {
depth: 40,
steps: 1,
bevelEnabled: true,
bevelThickness: 2,
bevelSize: 4,
bevelSegments: 1
};
const geometry3 = new THREE.ExtrudeGeometry( shape2, extrudeSettings3 );
const mesh3 = new THREE.Mesh( geometry3 );
mesh3.position.set( 150, 100, 0 );
}
function animate() {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
}
</script>
Currently, everything is based on splines. The result should not be based on extrusion, but on random points. I don't really know how to get random points. Is there a special function for it? Or can another function be used for it?
I would be veeeery thankful for help! :)
I think a good place to start with is using ConvexGeometry. You give it an array of points / Vector3 ( which I see you have created under the variable randomPoints ) as a parameter and it will create a shape for you.
I see you used CatmullRomCurve3, this may be a good tool to create the curves between the points as you mentioned. We can combine both of these ideas to create a somewhat curvier model.
const divisions = 25; // The amount of divisions between points
const catmullPoints = new THREE.CatmullRomCurve3( randomPoints, true, "catmullrom", 0.5 ).getPoints(divisions);
const geometryConvex = new ConvexGeometry( randomPoints );
So now you have a geometry with a somewhat randomized shape. The thing about it is that it will look a bit more "geometrical" than the example shapes you provided. So what you can try to do is divide your randomPoints to chunks, i.e multiple sub-arrays, and do a similar approach as above, basically saving the created geometries to a separate array, let's call it geometries, and then you can use mergeBufferGeometries to create a single geometry out of these geometries, this will give a more abstract looking shape. The code:
const size = THREE.MathUtils.randInt(2,10); // the number of sub arrays can be another parameter to randomize
const pointsChunk = chunk([...randomPoints], size); // you can use lodash or other chunk algorithms found online
const geometries = [];
for ( let i = 0 ; i < pointsChunk.length ; i++) {
const divisions = 25;
const catmullPoints = new THREE.CatmullRomCurve3( pointsChunk[i], true, "catmullrom", 0.5 ).getPoints( divisions );
geometries.push(new ConvexGeometry( catmullPoints ));
}
const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries( geometries );
There may be more ways to go about it, but I believe ConvexGeometry is definitely a good place to start.
Here is a fiddle of my attempt : https://jsfiddle.net/9rc503tn/2
I am using this example for my WebGL panorama cube: https://threejs.org/examples/?q=pano#webgl_panorama_equirectangular
I want to know what cube user clicks on and I discovered I can use Raycaster for this. According to docs I added the following function:
function onMouseDown( event ) {
event.preventDefault();
var mouseVector = new THREE.Vector3(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
1 );
//projector.unprojectVector( mouseVector, camera );
mouseVector.unproject( camera );
var raycaster = new THREE.Raycaster( camera.position, mouseVector.sub( camera.position ).normalize() );
// create an array containing all objects in the scene with which the ray intersects
var intersects = raycaster.intersectObjects( scene.children );
console.log(intersects);
if (intersects.length>0){
console.log("Intersected object:", intersects.length);
intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
}
// ...
But intersects is always empty. My scene is defined as
scene = new THREE.Scene();
and has skyBox added:
var skyBox = new THREE.Mesh( new THREE.CubeGeometry( 1, 1, 1 ), materials );
skyBox.applyMatrix( new THREE.Matrix4().makeScale( 1, 1, - 1 ) );
scene.add( skyBox );
I've seen similar posts related to this issue but could not figure out how to apply to this example. Any directions are appreciated.
Try adding this to your material definition:
var materials = new THREE.SomeMaterial({
/* other settings */,
side: THREE.DoubleSide
});
Raycaster won't intersect back-faces unless the side property is set to THREE.BackSide or THREE.DoubleSide. Even though your scaling technically inverts the face direction, the vertex order stays the same, which is what's important to Raycaster.
Some further explanation
The snippet below is showing how a ray projected from a camera at the center of a skybox inverted by a -Z scale might look.
The box itself looks weird because it has been -Z scaled, and the normals no longer match the material. But that's here nor there.
The green arrow represents the original ray. The red arrow represents what will happen to that ray inside the Mesh.raycast function, which will apply the inverse of the object's world matrix to the ray, but not to the object's geometry. This is a whole different problem.
The point I'm making is that within Mesh.raycast, it does not affect the vertex/index order, so when it checks the triangles of the mesh, they are still in their original order. For a standard BoxGeometry/BoxBufferGeometry, this means the faces all face outward from the geometric origin.
This means the rays (regardless of how the transformation matrix affects them) are still trying to intersect the back-face of those triangles, which will not work unless the material is set to THREE.DoubleSide. (It can also be set to THREE.BackSide, but the -Z scale will ruin that.)
Clicking either of the raycast buttons will produce 0 intersects if the -Z scaled box is not set to THREE.DoubleSide (default). Click the "Set THREE.DoubleSide" button and try it again--it will now intersect.
var renderer, scene, camera, controls, stats;
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight,
FOV = 35,
NEAR = 1,
FAR = 1000,
ray1, ray2, mesh;
function populateScene(){
var cubeGeo = new THREE.BoxBufferGeometry(10, 10, 10),
cubeMat = new THREE.MeshPhongMaterial({ color: "red", transparent: true, opacity: 0.5 });
mesh = new THREE.Mesh(cubeGeo, cubeMat);
mesh.applyMatrix( new THREE.Matrix4().makeScale( 1, 1, -1 ) );
mesh.updateMatrixWorld(true);
scene.add(mesh);
var dir = new THREE.Vector3(0.5, 0.5, 1);
dir.normalize();
ray1 = new THREE.Ray(new THREE.Vector3(), dir);
var arrow1 = new THREE.ArrowHelper(ray1.direction, ray1.origin, 20, 0x00ff00);
scene.add(arrow1);
var inverseMatrix = new THREE.Matrix4();
inverseMatrix.getInverse(mesh.matrixWorld);
ray2 = ray1.clone();
ray2.applyMatrix4(inverseMatrix);
var arrow2 = new THREE.ArrowHelper(ray2.direction, ray2.origin, 20, 0xff0000);
scene.add(arrow2);
}
function init() {
document.body.style.backgroundColor = "slateGray";
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
document.body.appendChild(renderer.domElement);
document.body.style.overflow = "hidden";
document.body.style.margin = "0";
document.body.style.padding = "0";
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(FOV, WIDTH / HEIGHT, NEAR, FAR);
camera.position.z = 50;
scene.add(camera);
controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.dynamicDampingFactor = 0.5;
controls.rotateSpeed = 3;
var light = new THREE.PointLight(0xffffff, 1, Infinity);
camera.add(light);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0';
document.body.appendChild(stats.domElement);
resize();
window.onresize = resize;
populateScene();
animate();
var rayCaster = new THREE.Raycaster();
document.getElementById("greenCast").addEventListener("click", function(){
rayCaster.ray.copy(ray1);
alert(rayCaster.intersectObject(mesh).length + " intersections!");
});
document.getElementById("redCast").addEventListener("click", function(){
rayCaster.ray.copy(ray2);
alert(rayCaster.intersectObject(mesh).length + " intersections!");
});
document.getElementById("setSide").addEventListener("click", function(){
mesh.material.side = THREE.DoubleSide;
mesh.material.needsUpdate = true;
});
}
function resize() {
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
if (renderer && camera && controls) {
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
controls.handleResize();
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
controls.update();
stats.update();
}
function threeReady() {
init();
}
(function () {
function addScript(url, callback) {
callback = callback || function () { };
var script = document.createElement("script");
script.addEventListener("load", callback);
script.setAttribute("src", url);
document.head.appendChild(script);
}
addScript("https://threejs.org/build/three.js", function () {
addScript("https://threejs.org/examples/js/controls/TrackballControls.js", function () {
addScript("https://threejs.org/examples/js/libs/stats.min.js", function () {
threeReady();
})
})
})
})();
body{
text-align: center;
}
<input id="greenCast" type="button" value="Cast Green">
<input id="redCast" type="button" value="Cast Red">
<input id="setSide" type="button" value="Set THREE.DoubleSide">
You might actually want to use an easier process to determine your ray from the camera:
THREE.Raycaster.prototype.setFromCamera( Vector2, Camera );
Simply define your mouse coordinates as you do in a Vector2, then pass the elements to the Raycaster and let it do its thing. It hides the complexity of intersecting the frustrum with the ray from the camera, and should solve your problem.
(Also, the raycaster does indeed only intersect faces that face the ray directly, but since your SkyBox has been inverted its geometries faces are pointing to the inside of the box, so they should intersect if the camera is inside the box. Another possibility is that your box is further away than the raycasters default far value.)
function onMouseDown( event ) {
event.preventDefault();
var mouseVector = new THREE.Vector2(
event.clientX / window.innerWidth * 2 - 1,
-event.clientY / window.innerHeight * 2 + 1
);
var raycaster = new THREE.Raycaster;
raycaster.setFromCamera( mouseVector, camera );
var intersects = raycaster.intersectObjects( scene.children );
console.log(intersects);
if( intersects.length > 0 ){
console.log( "Intersected object:", intersects[ 0 ] );
intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
}
}
I have the following JavaScript code, taken from an example, which draws some circles, and when you click on one of them, it changes color. But I also want to change the radius/size of a circle when you click on that circle (and leave the other circles unchanged). The documentation does not help at all, and I have tried several variations in the code like
intersects[ 0 ].object.geometry.parameters.radius = 50;
intersects[ 0 ].object.geometry.radius = 50;
intersects[ 0 ].object.geometry.setRadius(50);
Anyway, here is the complete code:
var container, camera, scene, geometry, mesh, renderer, controls, particles, colors;
var objects = [];
// DOM element...
container = document.createElement('div');
document.body.appendChild(container);
// Camera...
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 0, 75);
// Scene...
scene = new THREE.Scene();
scene.add(camera);
// Renderer...
renderer = new THREE.WebGLRenderer({
clearAlpha: 1
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xffffff, 1);
document.body.appendChild(renderer.domElement);
// Scatter plot...
scatterPlot = new THREE.Object3D();
scene.add(scatterPlot);
// Make grid...
xzColor = 'black';
xyColor = 'black';
yzColor = 'black';
// Plot some random points...
circle = new THREE.CircleGeometry(5);
colors = [];
var max = 50;
var min = -50;
for (var i = 0; i < 10; i++) {
var object = new THREE.Mesh( circle, new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, opacity: 0.5 } ) );
object.position.x = Math.random() * (max - min) + min;
object.position.y = Math.random() * (max - min) + min;
object.position.z = 0;
scene.add( object );
objects.push( object );
}
animate();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
function onDocumentMouseDown( event ) {
event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( objects );
if ( intersects.length > 0 ) {
intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
intersects[ 0 ].object.geometry.setRadius(50);
var particle = new THREE.Sprite( particleMaterial );
particle.position.copy( intersects[ 0 ].point );
particle.scale.x = particle.scale.y = 16;
scene.add( particle );
}
}
Any idea how I can solve this? And where can I find the proper documentation?
Addendum:
I have used the following line of code:
intersects[ 0 ].object.geometry.scale(1.1,1.1,1.1);
In the code, and now the circles change their size. But ALL of them! I click on one circle, and every circle changes size. Does not make sense to me...
Don't scale your geometry. You're using the same geometry reference for all of your circles, so scaling one scales them all.
Instead, scale your Mesh, which is a unique object in the scene (even if it references the same geometry as other meshes). Much like how you're setting position for each Mesh, you also have access to scale:
intersects[0].object.scale.set(1.1, 1.1, 1.1);
That will scale the intersected Mesh object, and only that Mesh.
Cloning and creating a new Mesh is literally introducing a memory leak. The original Mesh won't go away until you remove it from the scene, and you keep making more and more Geometry objects as you clone the circle.
Sorry for posting possible duplicate.
I have two 3d vectors:
center ( 0, 0, 0 )
orb ( 0, 0, 100 )
I want to rotate the orb-vector around the center-vector on both X and the Y axes.
What I'm trying to achieve is the make and object always be in view of the camera in the direction it's facing.
I've tried this but with no luck.
var vector = new THREE.Vector3( 0, 0, 100 );
vector.applyAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI * 0.5 );
vector.applyAxisAngle( new THREE.Vector3( 1, 0, 0 ), Math.PI * 0.5 );
orbBall.position.copy(vector);
"What I'm trying to achieve is the make and object always be in view of the camera in the direction it's facing."
If you are simply trying to ensure that orbBall always faces the camera, and both orbBall and the camera are part of the THREE scene then you can just use lookAt like so:
orbBall.lookAt(camera.position);
if you need to align a particular side of orbBall you can use a null dummy Object3D to do it, by adding the dummy node to the scene and orbBall to the dummy, in something like this:
dummy = new THREE.Object3D();
scene.add(camera); // "camera" is defined however
scene.add(dummy);
dummy.add(orbBall); // "orbBall" is created as usual
// ... not to align dummy+orbBall
dummy.lookAt(camera.position);
// ...and you can just rotate orbBall around "inside" dummy, just once,
/// to face however you like
After digging around this issue I realise that it's quite advanced mathematics.
Check out this lecture about quaternions if you're interested:
https://www.youtube.com/watch?v=mHVwd8gYLnI
So I used #bjorke suggestins and used a dummy object, and it works well.
var container, scene, camera, renderer, controls, stats;
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
camera.position.set(100, 100, 400);
camera.lookAt(scene.position);
scene.add(camera);
renderer = new THREE.WebGLRenderer( {antialias:true} );
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.getElementById( 'ThreeJS' );
container.appendChild( renderer.domElement );
var light = new THREE.DirectionalLight(0xffffff); //new THREE.PointLight(0xffffff);
light.position.set( 30, 80, -15 );
scene.add(light);
var boxGeo = new THREE.BoxGeometry( 10, 10, 10);
var axes = new THREE.AxisHelper(1000);
scene.add( axes );
var cameraObj = new THREE.Mesh(boxGeo, new THREE.MeshLambertMaterial( {color: 0x888800}));
scene.add(cameraObj);
var orbSpace = new THREE.Object3D();
scene.add(orbSpace);
var orbBall = new THREE.Mesh(boxGeo, new THREE.MeshLambertMaterial( {color: 0x880088}));
orbBall.position.set(0, 0, cameraObj.position.z + 100);
orbSpace.add(orbBall);
animate();
var camX = 0.3;
var camY = 0;
function animate() {
requestAnimationFrame( animate );
camY += 0.02;
if (camY >= 2) camY = 0;
cameraObj.rotation.x = Math.PI * document.querySelector('#volume').value;
cameraObj.rotation.y = Math.PI * camY;
orbSpace.position.copy(cameraObj.position);
orbSpace.rotation.copy(cameraObj.rotation)
renderer.render( scene, camera );
}
Here's a codepen about how it works:
http://codepen.io/arpo/pen/RrpMJJ
You can update the X angle in the uper right corner
I am trying to input some known acr values from another program and reproduce them in three.js
Right now I am using the following code I found on this site. It draw the arc fine, although it may not be the best option.
function DRAWarc(){
// smooth my curve over this many points
var numPoints = 100;
spline = new THREE.SplineCurve3([
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0, 200, 0),
new THREE.Vector3(150, 150, 0)
]);
var material = new THREE.LineBasicMaterial({
color: 0xff00f0,
});
var geometry = new THREE.Geometry();
var splinePoints = spline.getPoints(numPoints);
for(var i = 0; i < splinePoints.length; i++){
geometry.vertices.push(splinePoints[i]);
}
var line = new THREE.Line(geometry, material);
scene.add(line);
}
The following are the known variables.
Center point (X,Y) (if the are was a complete circle, the center of the circle)
radius (if it were a circle)
start angle (I'm not positive, but I think this is the degree, if it were a circle, going counter-clockwise, with 0 being to the right of the circle)
end angle (see above)
more code!
///////////
// SCENE //
///////////
scene = new THREE.Scene();
////////////
// CAMERA //
////////////
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
viewsize = 900;
camera = new THREE.OrthographicCamera(
SCREEN_WIDTH / - 2, SCREEN_WIDTH / 2,
SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2,
1, 1e6 );
camera.position.z = 2000;
scene.add(camera);
camera.lookAt(new THREE.Vector3(2100, 3600, 0));
//////////////
// RENDERER //
//////////////
// create and start the renderer
if ( Detector.webgl ){
renderer = new THREE.WebGLRenderer();
//alert('no problem.');
}else{
renderer = new THREE.CanvasRenderer();
alert('problem.');
}
renderer.setClearColor("white", 1);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.body;
container.appendChild( renderer.domElement );
////////////
// EVENTS //
////////////
// automatically resize renderer
THREEx.WindowResize(renderer, camera);
// toggle full-screen on given key press
THREEx.FullScreen.bindKey({ charCode : 'm'.charCodeAt(0) });
///////////
// STATS //
///////////
// displays current and past frames per second attained by scene
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.bottom = '0px';
stats.domElement.style.zIndex = 100;
container.appendChild( stats.domElement );
///////////
// LIGHT //
///////////
// create a light
var light = new THREE.PointLight(0xffffff);
light.position.set(0,250,0);
scene.add(light);
var ambientLight = new THREE.AmbientLight(0x111111);
// scene.add(ambientLight);
//////////////
// GEOMETRY //
//////////////
// most objects displayed are a "mesh":
// a collection of points ("geometry") and
// a set of surface parameters ("material")
doWork();
}
function animate()
{
requestAnimationFrame( animate );
render();
update();
}
function update()
{
// delta = change in time since last call (in seconds)
var delta = clock.getDelta();
// functionality provided by THREEx.KeyboardState.js
if ( keyboard.pressed("1") )
document.getElementById('message').innerHTML = ' Have a nice day! - 1';
if ( keyboard.pressed("2") )
document.getElementById('message').innerHTML = ' Have a nice day! - 2 ';
//controls.update();
stats.update();
}
function render()
{
renderer.render( scene, camera );
}`
You can draw arc with the circle geometry
// compute angle between p1 and p2
var angle = Math.acos(p1.dot(p2)/(p1.length()*p2.length()));
// create arc
var geometry = new THREE.CircleGeometry(radius, nbSegments, 0, angle);
// remove center vertex
geometry.vertices.splice(0,1);
// TODO: move the arc to the good place in the scene
// add arc to the scene
scene.add(new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: 0xff00f0 }));
So after a little research I found the following post.
How do I calculate a point on a circle’s circumference?
which led me to this bit of math that can be adapted to any language:
x = cx + r * cos(a)
y = cy + r * sin(a)
Where r is the radius, cx,cy the origin, and a the angle from 0..2PI radians or 0..360 degrees.
and heres some fun reading material!
http://en.wikipedia.org/wiki/Circle#Equations
EDIT: just completed the rough draft for this project. enjoi!
i does not draw a spline, instead it draws a line with 102 points. the start of the arc, the end, and 100 evenly spaced points in between. it works well, and i will add a variable to the number of lines to reduce memory if needed.
function getARC(x, y, r, a){
a = a * (Math.PI/180);
var ax = +x + +r * Math.cos(+a),
ay = +y + +r * Math.sin(+a),
res = [];
res['x'] = ax,
res['y'] = ay;
return res;
}
function DRAWarc(cx, cy, ra, sa, ea){
var cx = '2473.5737';
var cy = '3145.1300';
var ra = '47.5538';
var sa = '2';
var ea = '91';
var material = new THREE.LineBasicMaterial({
color: 0xff00f0,
});
var geometry = new THREE.Geometry();
var s = getARC(cx, cy, ra, sa);
geometry.vertices.push(new THREE.Vector3(s['x'], s['y'], 0));
var step = (ea - sa)/100;
for(var i=1;i<=100;i++){
var t = getARC(cx, cy, ra, (+sa + (+step * +i)));
geometry.vertices.push(new THREE.Vector3(t['x'], t['y'], 0));
//alert((+sa + (+step * +i)));
}
var f = getARC(cx, cy, ra, ea);
geometry.vertices.push(new THREE.Vector3(f['x'], f['y'], 0));
var line = new THREE.Line(geometry, material);
scene.add(line);
}