(THREE.JS) calculate the custom UVs for custom Buffer Geometry - javascript

I am trying to create a curve wall using some vertices array in three JS.
What I will get in array is some base vertices in 2D which will be the bottom vertices of wall. These includes the center, lower and upper vertices which means it is two faced wall. based on these vertices, I added some wall height and convert that 2D to 3D.
Below is the code and working fiddle
/**
* Created by Singh on 7/30/2018.
*/
var renderer, scene, camera;
init();
animate();
function init() {
wallsGeometry = function(totalPoints){
var material = new THREE.MeshBasicMaterial({/*color: 0xff0000,*/ side: THREE.DoubleSide, wireframe : false});
var material2 = new THREE.MeshBasicMaterial({/*color: 0x0044400, */side: THREE.DoubleSide, wireframe : true});
var geometry = new THREE.BufferGeometry();
var geometry2 = new THREE.BufferGeometry();
var wallHeight = 200;
var pointindices = [
0,1,2,0,2,3, //left
5,4,7,5,7,6, //right
4,0,3,4,3,7, //back
1,5,6,1,6,2, //front
2,6,7,2,7,3, //top
5,1,0,5,0,4, //bottom
];
var pointindices2 = [
1,0,2,1,3,2 , //left
4,5,7,4,6,7, //right
0,4,3,0,7,3, //back
5,1,2,5,2,6, //front
6,2,7,6,3,7, //top
1,5,0,1,4,0, //bottom
];
var tempIndices = [];
var tempIndices2 = [];
for(var i=0; i<4; i++) {
for (var j = 0; j < pointindices.length; j++) {
tempIndices[pointindices.length * i + j] = 4 * i + pointindices[j];
}
}
for(var i=0; i<4; i++) {
for (var j = 0; j < pointindices2.length; j++) {
tempIndices2[pointindices2.length * i + j] = 4 * i + pointindices2[j];
}
}
var tempVerMesh = [];
var tempVerMesh2 = [];
var indices = new Uint32Array( tempIndices );
var pointsArray = { // for testing
pointUpper1: new THREE.Vector3(),
pointUpper2: new THREE.Vector3(),
pointCenter1: new THREE.Vector3(),
pointCenter2: new THREE.Vector3(),
pointLower1: new THREE.Vector3(),
pointLower2: new THREE.Vector3()
};
console.log(totalPoints);
/*function generateUVs(geometry) {
geometry.computeBoundingBox();
var max = geometry.boundingBox.max, min = geometry.boundingBox.min;
var offset = new THREE.Vector3(0 - min.x, 0 - min.y);
var range = new THREE.Vector3(max.x - min.x, max.y - min.y);
var faces = geometry.faces;
geometry.faceVertexUvs[0] = [];
for (var i = 0; i < faces.length ; i++) {
var v1 = geometry.vertices[faces[i].a],
v2 = geometry.vertices[faces[i].b],
v3 = geometry.vertices[faces[i].c];
geometry.faceVertexUvs[0].push([
new THREE.Vector3((v1.x + offset.x)/range.x ,(v1.y + offset.y)/range.y),
new THREE.Vector3((v2.x + offset.x)/range.x ,(v2.y + offset.y)/range.y),
new THREE.Vector3((v3.x + offset.x)/range.x ,(v3.y + offset.y)/range.y),
]);
}
geometry.uvsNeedUpdate = true;
return geometry;
}*/
for (var i = 0; i < totalPoints.lower.length ; i++) {
pointsArray.pointCenter1 = totalPoints.center[i];
//pointsArray.pointCenter2 = totalPoints.center[i + 1];
pointsArray.pointLower1 = totalPoints.lower[i];
//pointsArray.pointLower2 = totalPoints.lower[i + 1];
pointsArray.pointUpper1 = totalPoints.upper[i];
//pointsArray.pointUpper2 = totalPoints.upper[i + 1];
tempVerMesh.push(pointsArray.pointCenter1.x, pointsArray.pointCenter1.y, pointsArray.pointCenter1.z);
tempVerMesh.push(pointsArray.pointLower1.x, pointsArray.pointLower1.y, pointsArray.pointLower1.z);
tempVerMesh.push(pointsArray.pointLower1.x, pointsArray.pointLower1.y + wallHeight, pointsArray.pointLower1.z);
tempVerMesh.push(pointsArray.pointCenter1.x, pointsArray.pointCenter1.y + wallHeight, pointsArray.pointCenter1.z);
tempVerMesh2.push(pointsArray.pointCenter1.x, pointsArray.pointCenter1.y, pointsArray.pointCenter1.z);
tempVerMesh2.push(pointsArray.pointUpper1.x, pointsArray.pointUpper1.y, pointsArray.pointUpper1.z);
tempVerMesh2.push(pointsArray.pointUpper1.x, pointsArray.pointUpper1.y + wallHeight, pointsArray.pointUpper1.z );
tempVerMesh2.push(pointsArray.pointCenter1.x, pointsArray.pointCenter1.y + wallHeight, pointsArray.pointCenter1.z);
}
var vertices = new Float32Array(tempVerMesh);
var vertices2 = new Float32Array(tempVerMesh2);
//var uvs = new Float32Array(pointUVs);
geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.setIndex(new THREE.BufferAttribute(indices, 1));
//geometry.addAttribute('uv', new THREE.BufferAttribute(uvs, 2));
geometry.computeFaceNormals();
geometry.computeVertexNormals();
console.log(geometry);
var mesh = new THREE.Mesh(geometry, material);
var indices2 = new Uint32Array(tempIndices2);
geometry2.addAttribute('position', new THREE.BufferAttribute(vertices2, 3));
geometry2.setIndex(new THREE.BufferAttribute(indices2, 1));
geometry2.computeFaceNormals();
geometry2.computeVertexNormals();
/*var geom = new THREE.Geometry().fromBufferGeometry(geometry2);
var temp = generateUVs(geom);
geometry2 = new THREE.BufferGeometry().fromGeometry(temp);*/
var mesh2 = new THREE.Mesh(geometry2, material2);
//geometry2.addAttribute('uv', new THREE.BufferAttribute(uvs2, 2));
return [mesh,mesh2];
};
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 400;
scene = new THREE.Scene();
var arrow;
var rayCaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
renderer.domElement.addEventListener("mousemove", onMouseMove);
var points = {
pointUpper1: new THREE.Vector3(-70, 0, -20),
pointUpper2: new THREE.Vector3(130, 0, -20),
pointCenter1: new THREE.Vector3(-100, 0, 0),
pointCenter2: new THREE.Vector3(150, 0, 0),
pointLower1: new THREE.Vector3(-70, 0, 20),
pointLower2: new THREE.Vector3(130, 0, 20)
};
var totalPoints = {
center : [new THREE.Vector3(-70, 0, 0),new THREE.Vector3(0, 0, 0),new THREE.Vector3(50, 0, 0),new THREE.Vector3(100, 0, 0),new THREE.Vector3(130, 0, 0)],
lower : [new THREE.Vector3(-70, 0, 20),new THREE.Vector3(0, 0, 20),new THREE.Vector3(50, 0, 20),new THREE.Vector3(100, 0, 20),new THREE.Vector3(130, 0, 20)],
upper : [new THREE.Vector3(-70, 0, -20),new THREE.Vector3(0, 0, -20),new THREE.Vector3(50, 0, -20),new THREE.Vector3(100, 0, -20),new THREE.Vector3(130, 0, -20)]
};
var sphere = new THREE.SphereGeometry(2, 10, 10);
function initPoints(){
var point1mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({color: 0xff00}));
point1mesh.position.copy(points.pointUpper1);
scene.add(point1mesh);
var point2mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({color: 0x0000ff}));
point2mesh.position.copy(points.pointUpper2);
scene.add(point2mesh);
var point3mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({color: 0xff00}));
point3mesh.position.copy(points.pointCenter1);
scene.add(point3mesh);
var point4mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({color: 0x0000ff}));
point4mesh.position.copy(points.pointCenter2);
scene.add(point4mesh);
var point5mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({color: 0xff00}));
point5mesh.position.copy(points.pointLower1);
scene.add(point5mesh);
var point6mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({color: 0x0000ff}));
point6mesh.position.copy(points.pointLower2);
scene.add(point6mesh);
}
initPoints();
var mesh = new wallsGeometry(totalPoints);
function createArrow() {
var length = 30;
arrow = new THREE.ArrowHelper(
THREE.Object3D.DefaultUp,
new THREE.Vector3(),
length,
0xffff00,
1.5 * length,
1.25 * length
);
arrow.position.z = 10;
scene.add(arrow);
}
// arrow
createArrow();
function updateArrow(object, point, face) {
arrow.position.copy(point);
var normalMatrix = new THREE.Matrix3().getNormalMatrix( object.matrixWorld );
var normal = face.normal.clone().applyMatrix3( normalMatrix ).normalize();
arrow.setDirection(normal);
}
function onMouseMove(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
rayCaster.setFromCamera(mouse, camera);
var intersects = rayCaster.intersectObject(mesh[0], true);
var i, il, intersect;
if (intersects[0]) {
var face = intersects[0].face;
var point = intersects[0].point;
var object = intersects[0].object;
updateArrow(object, point, face);
}
}
/* var textureLoader = new THREE.TextureLoader();
textureLoader.load('./textures/Capture.PNG', function (texture) {
console.log('texture loaded');
texture.minFilter = THREE.LinearFilter;
//mesh[0].material.map = texture;
var vertexNormalsHelper = new THREE.VertexNormalsHelper( mesh[0], 10 );
mesh[0].add( vertexNormalsHelper );
}); */
scene.add(mesh[0]);
/* textureLoader.load('./textures/abc.jpg', function (texture) {
console.log('texture loaded');
texture.minFilter = THREE.LinearFilter;
//mesh[1].material.map = texture;
var vertexNormalsHelper = new THREE.VertexNormalsHelper( mesh[1], 10 );
mesh[1].add( vertexNormalsHelper );
}); */
scene.add(mesh[1]);
//
var Orbitcontrols = new THREE.OrbitControls(camera,renderer.domElement);
Orbitcontrols.update();
}
// render
function render() {
renderer.render(scene, camera);
}
// animate
function animate() {
requestAnimationFrame(animate);
render();
}
https://jsfiddle.net/simar_aneja/fsmw8znq/6/
In the fiddle you can see that wall is building properly and you can increase the vertices and loop of creating those indices, in the start. Now I want to add UVs to this bufferGeometry, I tried converting to geometry and then calculated faceVertexUVs, but this is not the right way. Can anyone suggest me the further path where I can attach different textures only at the front side, different on top side. And it should be in such a way that no matter how many vertices comes, Uvs should get calculated based on length of vertices. I have some Idea but not getting how to make it different for diff sides of wall.
Thanks

Here's a UV box-unwrapping I fixed up for ya. Maybe you'll find it helpful...
I also put your fiddle into a snippet you can run below...
function boxUnwrapUVs(geometry) {
if (!geometry.boundingBox) geometry.computeBoundingBox();
var sz = geometry.boundingBox.getSize(new THREE.Vector3());
var center = geometry.boundingBox.getCenter(new THREE.Vector3())
var min = geometry.boundingBox.min;
if (geometry.faceVertexUvs[0].length == 0) {
for (var i = 0; i < geometry.faces.length; i++) {
geometry.faceVertexUvs[0].push([new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2()]);
}
}
for (var i = 0; i < geometry.faces.length; i++) {
var face = geometry.faces[i];
var faceUVs = geometry.faceVertexUvs[0][i]
var va = geometry.vertices[geometry.faces[i].a]
var vb = geometry.vertices[geometry.faces[i].b]
var vc = geometry.vertices[geometry.faces[i].c]
var vab = new THREE.Vector3().copy(vb).sub(va)
var vac = new THREE.Vector3().copy(vc).sub(va)
//now we have 2 vectors to get the cross product of...
var vcross = new THREE.Vector3().copy(vab).cross(vac);
//Find the largest axis of the plane normal...
vcross.set(Math.abs(vcross.x), Math.abs(vcross.y), Math.abs(vcross.z))
var majorAxis = vcross.x > vcross.y ? (vcross.x > vcross.z ? 'x' : vcross.y > vcross.z ? 'y' : vcross.y > vcross.z) : vcross.y > vcross.z ? 'y' : 'z'
//Take the other two axis from the largest axis
var uAxis = majorAxis == 'x' ? 'y' : majorAxis == 'y' ? 'x' : 'x';
var vAxis = majorAxis == 'x' ? 'z' : majorAxis == 'y' ? 'z' : 'y';
faceUVs[0].set((va[uAxis] - min[uAxis]) / sz[uAxis], (va[vAxis] - min[vAxis]) / sz[vAxis])
faceUVs[1].set((vb[uAxis] - min[uAxis]) / sz[uAxis], (vb[vAxis] - min[vAxis]) / sz[vAxis])
faceUVs[2].set((vc[uAxis] - min[uAxis]) / sz[uAxis], (vc[vAxis] - min[vAxis]) / sz[vAxis])
}
geometry.elementsNeedUpdate = geometry.verticesNeedUpdate = true;
}
geometry = new THREE.Geometry().fromBufferGeometry(geometry)
boxUnwrapUVs(geometry)
var mesh = new THREE.Mesh(geometry, material);
/**
* Created by Singh on 7/30/2018.
*/
var renderer, scene, camera;
init();
animate();
function init() {
wallsGeometry = function(totalPoints) {
var rrnd = (min, max) => (Math.random() * (max - min)) + min
var irnd = (rng) => (Math.random() * rng) | 0
function makeRndCanvas() {
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 128;
var ctx = canvas.getContext('2d');
var srnd = (rng) => (Math.random() - 0.5) * 2 * rng
var irnd = (rng) => ((Math.random() * rng) | 0)
for (var x = 0; x < canvas.width; x++) {
for (var y = 0; y < canvas.width; y++) {
ctx.fillStyle = `rgba(${irnd(256)},${irnd(256)},${irnd(256)},1.0)`
ctx.fillRect(x, y, 1, 1);
}
}
ctx.fillStyle = '#ffff00'
ctx.fillText("WAHOO", 3, 64)
return canvas;
}
function makeRndTexture() {
var tex = new THREE.Texture(makeRndCanvas())
tex.minFilter = // THREE.LinearMipMapLinearFilter;
tex.magFilter = THREE.NearestFilter; //THREE.LinearFilter;
tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
//tex.repeat.set(0.01, 0.01);
tex.needsUpdate = true;
return tex;
}
var material = new THREE.MeshLambertMaterial({ /*color: 0xff0000,*/
side: THREE.DoubleSide,
wireframe: false,
map: makeRndTexture()
});
var material2 = new THREE.MeshLambertMaterial({ /*color: 0x0044400, */
side: THREE.DoubleSide,
wireframe: true
});
var geometry = new THREE.BufferGeometry();
var geometry2 = new THREE.BufferGeometry();
var wallHeight = 200;
var pointindices = [
0, 1, 2, 0, 2, 3, //left
5, 4, 7, 5, 7, 6, //right
4, 0, 3, 4, 3, 7, //back
1, 5, 6, 1, 6, 2, //front
2, 6, 7, 2, 7, 3, //top
5, 1, 0, 5, 0, 4, //bottom
];
var pointindices2 = [
1, 0, 2, 1, 3, 2, //left
4, 5, 7, 4, 6, 7, //right
0, 4, 3, 0, 7, 3, //back
5, 1, 2, 5, 2, 6, //front
6, 2, 7, 6, 3, 7, //top
1, 5, 0, 1, 4, 0, //bottom
];
var tempIndices = [];
var tempIndices2 = [];
for (var i = 0; i < 4; i++) {
for (var j = 0; j < pointindices.length; j++) {
tempIndices[pointindices.length * i + j] = 4 * i + pointindices[j];
}
}
for (var i = 0; i < 4; i++) {
for (var j = 0; j < pointindices2.length; j++) {
tempIndices2[pointindices2.length * i + j] = 4 * i + pointindices2[j];
}
}
var tempVerMesh = [];
var tempVerMesh2 = [];
var indices = new Uint32Array(tempIndices);
var pointsArray = { // for testing
pointUpper1: new THREE.Vector3(),
pointUpper2: new THREE.Vector3(),
pointCenter1: new THREE.Vector3(),
pointCenter2: new THREE.Vector3(),
pointLower1: new THREE.Vector3(),
pointLower2: new THREE.Vector3()
};
console.log(totalPoints);
/*function generateUVs(geometry) {
geometry.computeBoundingBox();
var max = geometry.boundingBox.max, min = geometry.boundingBox.min;
var offset = new THREE.Vector3(0 - min.x, 0 - min.y);
var range = new THREE.Vector3(max.x - min.x, max.y - min.y);
var faces = geometry.faces;
geometry.faceVertexUvs[0] = [];
for (var i = 0; i < faces.length ; i++) {
var v1 = geometry.vertices[faces[i].a],
v2 = geometry.vertices[faces[i].b],
v3 = geometry.vertices[faces[i].c];
geometry.faceVertexUvs[0].push([
new THREE.Vector3((v1.x + offset.x)/range.x ,(v1.y + offset.y)/range.y),
new THREE.Vector3((v2.x + offset.x)/range.x ,(v2.y + offset.y)/range.y),
new THREE.Vector3((v3.x + offset.x)/range.x ,(v3.y + offset.y)/range.y),
]);
}
geometry.uvsNeedUpdate = true;
return geometry;
}*/
for (var i = 0; i < totalPoints.lower.length; i++) {
pointsArray.pointCenter1 = totalPoints.center[i];
//pointsArray.pointCenter2 = totalPoints.center[i + 1];
pointsArray.pointLower1 = totalPoints.lower[i];
//pointsArray.pointLower2 = totalPoints.lower[i + 1];
pointsArray.pointUpper1 = totalPoints.upper[i];
//pointsArray.pointUpper2 = totalPoints.upper[i + 1];
tempVerMesh.push(pointsArray.pointCenter1.x, pointsArray.pointCenter1.y, pointsArray.pointCenter1.z);
tempVerMesh.push(pointsArray.pointLower1.x, pointsArray.pointLower1.y, pointsArray.pointLower1.z);
tempVerMesh.push(pointsArray.pointLower1.x, pointsArray.pointLower1.y + wallHeight, pointsArray.pointLower1.z);
tempVerMesh.push(pointsArray.pointCenter1.x, pointsArray.pointCenter1.y + wallHeight, pointsArray.pointCenter1.z);
tempVerMesh2.push(pointsArray.pointCenter1.x, pointsArray.pointCenter1.y, pointsArray.pointCenter1.z);
tempVerMesh2.push(pointsArray.pointUpper1.x, pointsArray.pointUpper1.y, pointsArray.pointUpper1.z);
tempVerMesh2.push(pointsArray.pointUpper1.x, pointsArray.pointUpper1.y + wallHeight, pointsArray.pointUpper1.z);
tempVerMesh2.push(pointsArray.pointCenter1.x, pointsArray.pointCenter1.y + wallHeight, pointsArray.pointCenter1.z);
}
var vertices = new Float32Array(tempVerMesh);
var vertices2 = new Float32Array(tempVerMesh2);
//var uvs = new Float32Array(pointUVs);
geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.setIndex(new THREE.BufferAttribute(indices, 1));
//geometry.addAttribute('uv', new THREE.BufferAttribute(uvs, 2));
geometry.computeFaceNormals();
geometry.computeVertexNormals();
console.log(geometry);
function boxUnwrapUVs(geometry) {
if (!geometry.boundingBox) geometry.computeBoundingBox();
var sz = geometry.boundingBox.getSize(new THREE.Vector3());
var center = geometry.boundingBox.getCenter(new THREE.Vector3())
var min = geometry.boundingBox.min;
if (geometry.faceVertexUvs[0].length == 0) {
for (var i = 0; i < geometry.faces.length; i++) {
geometry.faceVertexUvs[0].push([new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2()]);
}
}
for (var i = 0; i < geometry.faces.length; i++) {
var face = geometry.faces[i];
var faceUVs = geometry.faceVertexUvs[0][i]
var va = geometry.vertices[geometry.faces[i].a]
var vb = geometry.vertices[geometry.faces[i].b]
var vc = geometry.vertices[geometry.faces[i].c]
var vab = new THREE.Vector3().copy(vb).sub(va)
var vac = new THREE.Vector3().copy(vc).sub(va)
//now we have 2 vectors to get the cross product of...
var vcross = new THREE.Vector3().copy(vab).cross(vac);
//Find the largest axis of the plane normal...
vcross.set(Math.abs(vcross.x), Math.abs(vcross.y), Math.abs(vcross.z))
var majorAxis = vcross.x > vcross.y ? (vcross.x > vcross.z ? 'x' : vcross.y > vcross.z ? 'y' : vcross.y > vcross.z) : vcross.y > vcross.z ? 'y' : 'z'
//Take the other two axis from the largest axis
var uAxis = majorAxis == 'x' ? 'y' : majorAxis == 'y' ? 'x' : 'x';
var vAxis = majorAxis == 'x' ? 'z' : majorAxis == 'y' ? 'z' : 'y';
faceUVs[0].set((va[uAxis] - min[uAxis]) / sz[uAxis], (va[vAxis] - min[vAxis]) / sz[vAxis])
faceUVs[1].set((vb[uAxis] - min[uAxis]) / sz[uAxis], (vb[vAxis] - min[vAxis]) / sz[vAxis])
faceUVs[2].set((vc[uAxis] - min[uAxis]) / sz[uAxis], (vc[vAxis] - min[vAxis]) / sz[vAxis])
}
geometry.elementsNeedUpdate = geometry.verticesNeedUpdate = true;
}
geometry = new THREE.Geometry().fromBufferGeometry(geometry)
boxUnwrapUVs(geometry)
geometry = new THREE.BufferGeometry().fromGeometry(geometry)
var mesh = new THREE.Mesh(geometry, material);
var indices2 = new Uint32Array(tempIndices2);
geometry2.addAttribute('position', new THREE.BufferAttribute(vertices2, 3));
geometry2.setIndex(new THREE.BufferAttribute(indices2, 1));
geometry2.computeFaceNormals();
geometry2.computeVertexNormals();
/* var geom = new THREE.Geometry().fromBufferGeometry(geometry2);
var temp = generateUVs(geom);
geometry2 = new THREE.BufferGeometry().fromGeometry(temp);*/
var mesh2 = new THREE.Mesh(geometry2, material2);
//geometry2.addAttribute('uv', new THREE.BufferAttribute(uvs2, 2));
return [mesh, mesh2];
};
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 400;
scene = new THREE.Scene();
var arrow;
var rayCaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
var light = new THREE.DirectionalLight();
light.position.set(200, 200, 200)
scene.add(light)
document.body.appendChild(renderer.domElement);
renderer.domElement.addEventListener("mousemove", onMouseMove);
var points = {
pointUpper1: new THREE.Vector3(-70, 0, -20),
pointUpper2: new THREE.Vector3(130, 0, -20),
pointCenter1: new THREE.Vector3(-100, 0, 0),
pointCenter2: new THREE.Vector3(150, 0, 0),
pointLower1: new THREE.Vector3(-70, 0, 20),
pointLower2: new THREE.Vector3(130, 0, 20)
};
var totalPoints = {
center: [new THREE.Vector3(-70, 0, 0), new THREE.Vector3(0, 0, 0), new THREE.Vector3(50, 0, 0), new THREE.Vector3(100, 0, 0), new THREE.Vector3(130, 0, 0)],
lower: [new THREE.Vector3(-70, 0, 20), new THREE.Vector3(0, 0, 20), new THREE.Vector3(50, 0, 20), new THREE.Vector3(100, 0, 20), new THREE.Vector3(130, 0, 20)],
upper: [new THREE.Vector3(-70, 0, -20), new THREE.Vector3(0, 0, -20), new THREE.Vector3(50, 0, -20), new THREE.Vector3(100, 0, -20), new THREE.Vector3(130, 0, -20)]
};
var sphere = new THREE.SphereGeometry(2, 10, 10);
function initPoints() {
var point1mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({
color: 0xff00
}));
point1mesh.position.copy(points.pointUpper1);
scene.add(point1mesh);
var point2mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({
color: 0x0000ff
}));
point2mesh.position.copy(points.pointUpper2);
scene.add(point2mesh);
var point3mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({
color: 0xff00
}));
point3mesh.position.copy(points.pointCenter1);
scene.add(point3mesh);
var point4mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({
color: 0x0000ff
}));
point4mesh.position.copy(points.pointCenter2);
scene.add(point4mesh);
var point5mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({
color: 0xff00
}));
point5mesh.position.copy(points.pointLower1);
scene.add(point5mesh);
var point6mesh = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({
color: 0x0000ff
}));
point6mesh.position.copy(points.pointLower2);
scene.add(point6mesh);
}
initPoints();
var mesh = new wallsGeometry(totalPoints);
function createArrow() {
var length = 30;
arrow = new THREE.ArrowHelper(
THREE.Object3D.DefaultUp,
new THREE.Vector3(),
length,
0xffff00,
1.5 * length,
1.25 * length
);
arrow.position.z = 10;
scene.add(arrow);
}
// arrow
createArrow();
function updateArrow(object, point, face) {
arrow.position.copy(point);
var normalMatrix = new THREE.Matrix3().getNormalMatrix(object.matrixWorld);
var normal = face.normal.clone().applyMatrix3(normalMatrix).normalize();
arrow.setDirection(normal);
}
function onMouseMove(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
rayCaster.setFromCamera(mouse, camera);
var intersects = rayCaster.intersectObject(mesh[0], true);
var i, il, intersect;
if (intersects[0]) {
var face = intersects[0].face;
var point = intersects[0].point;
var object = intersects[0].object;
updateArrow(object, point, face);
}
}
/* var textureLoader = new THREE.TextureLoader();
textureLoader.load('./textures/Capture.PNG', function (texture) {
console.log('texture loaded');
texture.minFilter = THREE.LinearFilter;
//mesh[0].material.map = texture;
var vertexNormalsHelper = new THREE.VertexNormalsHelper( mesh[0], 10 );
mesh[0].add( vertexNormalsHelper );
}); */
scene.add(mesh[0]);
/* textureLoader.load('./textures/abc.jpg', function (texture) {
console.log('texture loaded');
texture.minFilter = THREE.LinearFilter;
//mesh[1].material.map = texture;
var vertexNormalsHelper = new THREE.VertexNormalsHelper( mesh[1], 10 );
mesh[1].add( vertexNormalsHelper );
}); */
scene.add(mesh[1]);
//
var Orbitcontrols = new THREE.OrbitControls(camera, renderer.domElement);
Orbitcontrols.update();
}
// render
function render() {
renderer.render(scene, camera);
}
// animate
function animate() {
requestAnimationFrame(animate);
render();
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>

Related

Uncaught TypeError: Cannot read property 'position' of undefined THREE.js

This is my basic THREE.js code that I'm using to implement my Torus and Sphere game. I'm at the point of collision detection between the sphere and torus.
As stated, it has the error message Uncaught TypeError:
Cannot read property 'position' of undefined.
# lines 130 -
this.mesh.position.z += this.rate;//this.rate;
& # line 523 - obstacles[i].Update();
Why is this.mesh incorrect? Also, why isn't my for loop looping my clouds?
//var scene = new THREE.Scene(); // Create the scene and a camera to view it`enter code here`
//element.style.background-color;
// fogColor = new THREE.Color(0xCCCCCC); //Create colour of fog
// scene.background = fogColor;
// scene.fog = new THREE.Fog(fogColor, 0.25,30);
// Specify the portion of the scene visiable at any time (in degrees)
//var fieldOfView = 75;
// https://stackoverflow.com/questions/16177056/changing-three-js-background-to-transparent-or-other-color/31636198
var scene = new THREE.Scene(); // initialising the scene
scene.background = new THREE.Color( 0x87cefa ); //adding color to sky
//var renderer = new THREE.WebGLRenderer({ alpha: true });
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.5, 50 );
// var listener = new THREE.AudioListener();
// camera.add( listener );
// var sound = new THREE.Audio( listener );
// var audioLoader = new THREE.AudioLoader();
// audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
// sound.setBuffer( buffer );
// sound.setLoop( true );
// sound.setVolume( 0.5 );
// sound.play();
// });
var objects = [];
var obstacles = [];
var renderer = new THREE.WebGLRenderer();
var directionalLight = new THREE.DirectionalLight( 0xffffff, 2 );
directionalLight.position.set( 0, 1, 0 ); //default; light shining from top
directionalLight.castShadow = true; // default false
var ambientLight = new THREE.AmbientLight( 0x404040 );
directionalLight.shadow.camera.top = 10;
directionalLight.shadow.bottom = 10;
directionalLight.shadow.left = -10;
directionalLight.shadow.right = 10;
directionalLight.shadow.mapSize.width = 512; // default
directionalLight.shadow.mapSize.height = 512; // default
directionalLight.shadow.camera.near = 0.5; // default
directionalLight.shadow.camera.far = 500; // default
scene.add( ambientLight, directionalLight );
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
var planeGeometry = new THREE.PlaneGeometry( 30, 500 );
var planeMaterial = new THREE.MeshNormalMaterial();
var plane = new THREE.Mesh( planeGeometry, planeMaterial );
//var planeGeometry = new THREE.PlaneGeometry(0.05, 200, 320, 500);
plane.castShadow = false;
plane.receiveShadow = true;
scene.add( plane );
plane.rotation.x = -3.14159 * 0.5;
scene.add(plane);
plane.position.x = 0;
plane.position.y = 30;
plane.position.z = 0;
camera.position.z = 15;
camera.position.y = 0;
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
class Entity {
constructor() {
}
Update() {
}
Reset() {
}
}
class Ring1 extends Entity{
Constructor() {
// super();
this.collidable = true;
this.size = 5;
this.geometry = new THREE.TorusBufferGeometry( 2, 0.5, 10, 100 );
this.material = new THREE.MeshLambertMaterial( {color: 0xffff00} );
this.mesh = new THREE.Mesh( this.geometry, this.material );
this.mesh.castShadow = true;
this.mesh.receiveShadow = true;
this.mesh.position.x = 10;
this.mesh.position.y = 20;
this.mesh.position.z = -50;
//
// this.originalz = z;
// this.rate = rate;
this.speed = 0.2;
scene.add(this.mesh);
}
Update() {
super.Update();
// console.log("oops");
this.mesh.position.z += this.rate;//this.rate;
if(this.mesh.position.z > 0.5){
this.mesh.position.z = this.originalz;
this.speed += 0.015; // speeds up torus each refresh of position
// }
}
}
Reset(){
super.Reset();
}
}
for (i =0; i <3; i++){
var Donuts = new Ring1();
obstacles.push(Donuts);
}
var obstacleList = [];
var myTorus = new Ring1(-10, 1, -160, -1);
var myTorus1 = new Ring1(-5, 1, -30, -1);
var myTorus2 = new Ring1(0, 1, -90, -1);
var myTorus3 = new Ring1(0, 1, -120, -1);
var myTorus4 = new Ring1(10, 1, -60, -1);
obstacleList.push(myTorus1, myTorus2, myTorus3, myTorus4, myTorus );
class Obstacle extends Entity {
Constructor(x,y,z, rate) {
//super();
this.size = 5; // Must call super constructor in derived class before accessing 'this' or returning from derived constructor
this.collidable = true;
this.geometry = new THREE.TorusBufferGeometry( 2, 0.5, 10, 100 );
this.material = new THREE.MeshLambertMaterial( {color: 0xFF0000} );
this.ring = new THREE.Mesh( this.geometry, this.material );
this.ring.castShadow = true;
this.ring.receiveShadow = true;
this.ring.position.x = x;
this.ring.position.y = y;
this.ring.position.z = z;
this.origionalz = z;// this.rate = rate;
this.speed = 0.2;
scene.add(this.ring);
}
Update() {
this.ring.position.z += this.speed;//this.rate;
if(this.ring.position.z > 0.3){ //if torus reaches 0.3 of z axis then return t origional position
this.ring.position.z = this.origionalz;
this.speed += 0.025; // speeds up torus each refresh of position
//super.update();
}
}
Reset(){
super.reset();
}
}
var obstacleList2 = [];
var Villian = new Obstacle(-10, 1, -160, -1);
var Villian2 = new Obstacle(-5, 1, -260, -1);
var Villian3 = new Obstacle(0, 1, -60, -1);
var Villian4 = new Obstacle(5, 1, -200, -1);
var Villian5 = new Obstacle(10, 1, -300, -1);
obstacleList2.push(Villian, Villian2, Villian3, Villian4, Villian5);
class Service{ //like the idea of manager - they set tasks but dont do them personally
Constructor(){
}
Update(){
}
};
function onDocumentKeyDown(event) {
var keyCode = event.keyCode;
keyboard.keys[keyCode]=true;
};
function onDocumentKeyUp(event) {
var keyCode = event.keyCode;
keyboard.keys[keyCode]=false;
};
class KeyboardService extends Service{ // declliration of keyboard serive
Constructor(){
// super();
document.addEventListener("keydown", onDocumentKeyDown, false);
document.addEventListener("keyup", onDocumentKeyUp, false);
this.keys=[];
}
Update(){
}
IsKeydown(keyCode){
return this.keys[keyCode];
}
DocumentKeyDOwn(event){
var keyCode = event.keycode;
keyboard.keys[keyCode] = true;
}
DocumentKeyUp(event){
var keyCode = event.keyCode;
keybaord.key[keycode] = false;
}
};
var keyboard = new KeyboardService();
class Clouds extends Entity {
Constructor(x,y,z, rate) {
// super();
//this.geometry = new THREE.SphereGeometry( 2, 22, 52, -20);
//this.material = new THREE.MeshPhongMaterial( {color: 0xffffff} );
//this.mesh = new THREE.Mesh( this.geometry, this.material );
this.material = new THREE.MeshLambert({color:0xffffff});
this.geometry = new THREE.Geometry();
this.cloud1 = new THREE.SphereGeometry(7,3,2); //indiviual cloud
this.cloud1.translate(-9,0,0);
this.geometry.merge(this.cloud1)
this.cloud2 = new THREE.SphereGeometry(9,3,2);
this.cloud2.translate(0,0,0);
this.geometry.merge(this.cloud2)
this.cloud3 = new THREE.SphereGeometry(7,3,2);
this.cloud3.translate(9,0,0);
this.geometry.merge(this.cloud3)
this.cloud = new THREE.Mesh(this.geometry,this.material);
this.cloud.position.x = 10;
this.cloud.position.y = 20;
this.cloud.position.z = -20; //whole cloud meshed group positions
//PUT GET RANDOM
//this.mesh.position.x = x
//this.mesh.position.y = y
//this.mesh.position.z = z
// this.mesh.castShadow = true;
// this.mesh.receiveShadow = true;
scene.add(this.cloud);
}
Update() {
this.mesh.position.z += this.speed;//this.rate;
if(this.mesh.position.z > 0.3){ //if torus reaches 0.3 of z axis then return t origional position
this.mesh.position.z = this.origionalz;
this.speed += 0.015; // speeds up torus each refresh of position
document.getElementById('hud_distance').innerHTML = (this.mesh.position.z/1000).toFixed(2) + " km";
super.update();
}
}
Reset(){
super.reset();
}
}
//for (i = 0; i < 3; i++){ //UNCOMMENT & ADD GET RADNOM TO LINE 300
//var clouds = new Clouds
// objects.push(cloud)
//}
//var obstacleList3 = [];
//var cloud = new Cloud(-20, 10, -10, -1);
//var cloud1 = new Cloud(-22, 12, -10, -1);
//var cloud2 = new Cloud(-20, 10, -17, -1);
//var cloud3 = new Cloud(-22, 12, -19, -1);
//var cloud9 = new Cloud(-19, 12, -21, -1);
//var cloud4 = new Cloud(18, 10, -10, -1);
//var cloud5 = new Cloud(22, 12, -10, -1);
//var cloud6 = new Cloud(20, 10, -19, -1);
//var cloud7 = new Cloud(22, 12, -21, -1);
//var cloud8 = new Cloud(19, 12, -21, -1);
//var cloud10 = new Cloud(24, 10, -12, -1);
//var cloud11 = new Cloud(24, 10, -10, -1);
//cloud = new Cloud(-20, 10, -20, -1);
//var cloud11 = new Cloud(-22, 12, -20, -1);
//var cloud12 = new Cloud(-20, 10, -27, -1);
//var cloud13 = new Cloud(-22, 12, -29, -1);
//var cloud19 = new Cloud(-19, 12, -31, -1);
//var cloud14 = new Cloud(18, 10, -20, -1);
//var cloud15 = new Cloud(22, 12, -20, -1);
//var cloud16 = new Cloud(20, 10, -29, -1);
//var cloud17 = new Cloud(22, 12, -31, -1);
//var cloud18 = new Cloud(19, 12, -31, -1);
//var cloud20 = new Cloud(24, 10, -22, -1);
//obstacleList3.push(cloud, cloud1, cloud2, cloud3, cloud4, cloud5, cloud6, cloud7, cloud8, cloud9, cloud10, cloud11, cloud12, cloud13, cloud14, cloud15, cloud16, cloud17, cloud18, cloud19, cloud20);
class Sphere extends Entity{
constructor(x,y,z, rate) {
console.log("SPHERE CONS");
super();
this.collidable = false;
this.geometry1 = new THREE.SphereGeometry( 1, 22, 52, 0);
this.material1 = new THREE.MeshPhongMaterial( {color: 0xffff00} );
this.mesh = new THREE.Mesh( this.geometry1, this.material1 );
this.mesh.position.x = x
this.mesh.position.y = y
this.mesh.position.z = z
this.mesh.castShadow = true;
this.mesh.receiveShadow = true;
this.speed = rate;
this.speed = 0.0;
//this.origionalz = z;
scene.add(this.mesh);
}
update() {
// console.log("ball");
// console.log(this.mesh.position.x);
// console.log(this.mesh.position.y);
// console.log(this.mesh.position.z);
if (keyboard.IsKeydown(38) == true) {
this.mesh.position.y += 0.25;
}
if (keyboard.IsKeydown(40) == true) {
this.mesh.position.y -= 0.25;
}
if (keyboard.IsKeydown(37) == true) {
this.mesh.position.x -= 0.25;
}
if (keyboard.IsKeydown(39) == true) {
this.mesh.position.x += 0.25;
}
if (keyboard.IsKeydown(32) == true) {
this.mesh.position.x = 0;
this.mesh.position.y = 0;
this.mesh.position.z = 0;
}
if ( this.CollidedWithObstacle())
{
console.log(" ----- CRASH ---- ");
}
// {
// var keyCode = event.keyCode;
// if ( keyCode == 87 ) { //up
// sphere.position.y += 0.5;}
// else if (keyCode == 83) { //down
// sphere.position.y -= 0.5;
// } else if (keyCode == 65) { //left
// sphere.position.x -= 0.5;
// } else if (keyCode == 68) { // right
// sphere.position.x += 0.5;
// } else if (keyCode == 32) { //space = return to centre
// sphere.position.x = 0.0;
// sphere.position.y = 0.0;
// sphere.position.z = 0.0;
// }
this.mesh.position.z += this.speed;//this.rate;
if(this.mesh.position.z > 0.3){ //if sphere reaches 0.3 of z axis then return to origional position
this.mesh.position.z = this.origionalz;
// this.speed += 0.015; // speeds up sphere each refresh of position
}
if ( this.CollidedWithObstacle()){
console.log("BANG");
//this.sheild --- BANG---
}
}
Move(){
}
DistanceTo(x,z) {
let dist = Math.abs ( Math.sqrt(
(( this.mesh.position.x - x)* (this.mesh.position.x - x ))+
((this.mesh.position.z - z)* (this.mesh.position.z - z ))));
return dist;
}
IsCollidedWith(that){
let collidedWith = (this.size + that.size) > this.DistanceTo(that.mesh.position.x, that.mesh.position.z);
return collidedWith;
}
CollidedWithObstacle (){
for(var n=0; n<obstacles.length; n++){
if (obstacles[n].collidable == true){
if (this.IsCollidedWith(obstacles[n])==true){
return true;
}
}
}
return false;
}
Reset(){
}
}
var obstacleList4 = [];
var ball = new Sphere( 0, 0, 0, -0.01);
//var ball1 = new sphere( 3, 22, 52, -20);
obstacleList4.push(ball);
var cloud = new Clouds;
var avatar = new Sphere;
var rings = new Ring1;
var animate = function () {
requestAnimationFrame( animate );
renderer.render(scene, camera);
for (let i = 0; i < obstacleList.length; i++){
obstacleList[i].update();
}
for (let i = 0; i < obstacleList2.length; i++){
obstacleList2[i].update();
}
for (let i = 0; i < obstacleList3.length; i++){
obstacleList3[i].update();
}
for (let i = 0; i < obstacleList4.length; i++){
obstacleList4[i].update();
}
cloud.Update(); //constantly pushing update
avatar.Update();
rings.Update();
}
for (let i = 0; i < obstacles.length; i++){
obstacles[i].Update();
}
for (let i = 0; i <objects.lenght; i++){
objects[i].update();
}
animate();

How can I turn shaders off and on at specific points in my Three JS scene?

I am creating a THREEjs animation which I eventually want to sync with audio. (Can't accomplish this currently) I would like to add and remove shaders at specific points. How can I accomplish this most efficiently?
The way I have it set up now, is that I have a mirror shader inside of a function called turnOnMirror and in my render function, I have a conditional statement,
if (audioSrc.context.currentTime > 32.0) { turnOnMirror(); }
The shader looks like this:
var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
mirror.renderToScreen = true;
composer.addPass(mirror);
(I am doing this for 2 reasons!
A: The renderer is the only place I can grab the actual time to make this call. And B: because for whatever reason, my frequencyData array comes back as 0s.
However, when the scene reaches this point, everything slows down extremely. How can I keep the same frame rate and accomplish what I am attempting to at the same time?
A piece of information for you is that the scene works fine at the same constant speed if I just apply the shader without making the call in the render function.
You can view the site here!
And the source code for the main.js is below!
/* ==================== [ Global Variables ] ==================== */
var scene, camera, renderer, aspectRatio;
var stats;
var composer, effect, clock;
var backMesh;
/* ==================== [ Audio Context ] ==================== */
var ctx = new AudioContext();
var audio = document.getElementById('player');
audio.play();
audio.volume = 1;
// audio.crossOrigin = "anonymous";
var audioSrc = ctx.createMediaElementSource(audio);
var analyser = ctx.createAnalyser();
audioSrc.connect(analyser);
audioSrc.connect(ctx.destination);
// frequencyBinCount tells you how many values you'll receive from the analyser
var frequencyData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(frequencyData);
console.log(audioSrc);
console.log(audioSrc.context.currentTime);
console.log(frequencyData);
console.log(analyser.fftSize); // 2048 by default
console.log(analyser.frequencyBinCount); // will give us 1024 data points
analyser.fftSize = 64;
console.log(analyser.frequencyBinCount); // fftSize/2 = 32 data points
/* ==================== [ Set Scene & Camera ] ==================== */
scene = new THREE.Scene();
// scene.fog = new THREE.Fog(0x000000, 0, 1200);
aspectRatio = window.innerWidth / window.innerHeight;
camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 100);
// camera.target = new THREE.Vector3( 10, 10, 10 );
// Set the DOM
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor("#000000");
document.body.appendChild(renderer.domElement);
/* ==================== [ Camera Position ] ==================== */
camera.position.z = 15;
camera.position.y = 0;
/* ==================== [ Point Lights ] ==================== */
var pointLightBlue = new THREE.PointLight("#00ccff", 5, 100, 2);
pointLightBlue.position.set(-10, -40, -10);
scene.add(pointLightBlue);
// var pointLightWhite = new THREE.PointLight( "#ffffff", 1, 0, 1 );
// // pointLightWhite.position.set( -10, 160, -10 );
// pointLightWhite.position.set( 0, 0, 1 );
// scene.add(pointLightWhite);
// camera.add(pointLightWhite);
// var pointLightPink = new THREE.PointLight( "#EE567C", 5, 100, 10 );
// pointLightPink.position.set( 1, 0, -5 );
// scene.add(pointLightPink);
var pointLight = new THREE.PointLight("#A805FA", 2, 100, 40);
pointLight.position.set(40, 0, 40);
scene.add(pointLight);
var light2 = new THREE.PointLight( 0xFFFFFF, 1, 100 );
scene.add( light2 );
light2.position.z = 1000;
var pointLight2 = new THREE.PointLight("#07FAA0", 2, 100, 30);
pointLight2.position.set(-40, 0, -40);
scene.add(pointLight2);
/* ==================== [ Particles ] ==================== */
var getCamera = function() {
return camera;
}
// var texture = new Image();
// texture.src = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/82015/snowflake.png';
// texture.src = './images/particle.png';
//var material = new THREE.ParticleBasicMaterial( { map: new THREE.Texture(texture) } );
var particleCount = 0, particleSystem, particles;
THREE.ImageUtils.crossOrigin = '';
var texture = THREE.ImageUtils.loadTexture('./images/particle.png');
//console.log(texture);
particleCount = 20000,
particles = new THREE.Geometry();
var pMaterial = new THREE.PointCloudMaterial({
color: 0xFFFFFF,
map: texture,
blending: THREE.AdditiveBlending,
depthTest: false,
depthWrite: false,
transparent: true,
opacity: 0.3,
side: THREE.DoubleSide,
size: 1.2
});
for (var i = 0; i < particleCount; i++) {
var pX = Math.random() * 500 - 250,
pY = Math.random() * 500 - 250,
pZ = Math.random() * 500 - 250,
particle = new THREE.Vector3(pX, pY, pZ);
particles.vertices.push(particle);
}
particleSystem = new THREE.ParticleSystem(particles, pMaterial);
particleSystem.sortParticles = false;
particleSystem.frustumCulled = false;
scene.add(particleSystem);
/* ==================== [ Light Beams ] ==================== */
var BEAM_ROT_SPEED = 0.003;
var BEAM_COUNT = 360;
var beamGeometry = new THREE.PlaneBufferGeometry(1, 500, 10, 1);
beamGroup = new THREE.Object3D();
beamMaterial = new THREE.MeshBasicMaterial({
opacity: 0.02,
transparent: true,
});
for (var i = 0; i <= BEAM_COUNT; ++i) {
var beam = new THREE.Mesh(beamGeometry, beamMaterial);
beam.doubleSided = true;
beam.rotation.x = Math.random() * Math.PI;
beam.rotation.y = Math.random() * Math.PI;
beam.rotation.z = Math.random() * Math.PI;
beamGroup.add(beam);
}
scene.add(beamGroup);
beamGroup.translateZ( -5 );
/* ==================== [ Cubes ] ==================== */
var doStrobe = false;
var doShake = false;
var strobeOn = false;
var beatTime = 30;
THREE.ImageUtils.crossOrigin = '';
var imgTextureStripes2 = THREE.ImageUtils.loadTexture( "./images/stripes2.jpg" );
imgTextureStripes2.wrapS = imgTextureStripes2.wrapT = THREE.RepeatWrapping;
imgTextureStripes2.repeat.set( 100, 100 );
backMaterial2 = new THREE.MeshBasicMaterial( {
map:imgTextureStripes2
} );
backMesh2 = new THREE.Mesh( new THREE.SphereGeometry( 1900, 30, 20 ), backMaterial2 );
backMesh2.scale.x = -1;
scene.add( backMesh2 );
backMesh2.visible = false;
function Box() {
this.posn = new THREE.Vector3();
this.rotation = new THREE.Vector3();
this.speed = getRand(3, 20);
this.init();
}
Box.ORIGIN = new THREE.Vector3();
Box.MAX_DISTANCE = 1000;
Box.INIT_POSN_RANGE = 500;
Box.FRONT_PLANE_Z = 1000;
Box.BACK_PLANE_Z = -1000;
Box.prototype.init = function() {
this.posn.copy(Box.ORIGIN);
this.posn.x = getRand(-Box.INIT_POSN_RANGE,Box.INIT_POSN_RANGE);
this.posn.y = getRand(-Box.INIT_POSN_RANGE,Box.INIT_POSN_RANGE);
this.posn.z = Box.BACK_PLANE_Z;
this.rotation.x = (Math.random() * 360 ) * Math.PI / 180;
this.rotation.y = (Math.random() * 360 ) * Math.PI / 180;
this.rotation.z = (Math.random() * 360 ) * Math.PI / 180;
};
Box.prototype.update = function() {
this.posn.z += this.speed * sketchParams.cubeSpeed ;
this.rotation.x += 0.03;
this.rotation.y += 0.01;
if(this.posn.z > Box.FRONT_PLANE_Z) {
this.init();
}
};
// returns random number within a range
function getRand(minVal, maxVal) {
return minVal + (Math.random() * (maxVal - minVal));
}
var cubesize = 100;
var BOX_COUNT;
var geometry = new THREE.CubeGeometry(cubesize, cubesize, cubesize);
cubeHolder = new THREE.Object3D();
THREE.ImageUtils.crossOrigin = '';
imgTextureStripes = THREE.ImageUtils.loadTexture( "./images/stripes2.jpg" );
cubeMaterial = new THREE.MeshPhongMaterial( {
ambient: 0x111111,
color: 0x666666,
specular: 0x999999,
shininess: 30,
shading: THREE.FlatShading,
map:imgTextureStripes
});
for(i = 0; i < BOX_COUNT; i++) {
var box = new Box();
console.log(box);
boxes.push(box);
var cube = new THREE.Mesh(geometry,cubeMaterial );
cube.position = box.posn;
cube.rotation = box.rotation;
cube.ox = cube.scale.x = Math.random() * 1 + 1;
cube.oy = cube.scale.y = Math.random() * 1 + 1;
cube.oz = cube.scale.z = Math.random() * 1 + 1;
cubeHolder.add(cube);
}
scene.add(cubeHolder);
/* ==================== [ Mini Geometries ] ==================== */
/* ==================== [ Post Processing ] ==================== */
composer = new THREE.EffectComposer(renderer);
composer.addPass(new THREE.RenderPass(scene, camera));
effect = new THREE.ShaderPass(THREE.FilmShader);
effect.uniforms['time'].value = 2.0;
effect.uniforms['nIntensity'].value = 0.4;
effect.uniforms['sIntensity'].value = 0.9;
effect.uniforms['sCount'].value = 1800;
effect.uniforms['grayscale'].value = 0.8;
composer.addPass(effect);
// var dot = new THREE.ShaderPass( THREE.DotScreenShader );
// dot.uniforms[ 'scale' ].value = 400;
// dot.uniforms[ 'tDiffuse' ].value = 40;
// dot.uniforms[ 'tSize' ].value = new THREE.Vector2( 256, 256 );
// composer.addPass(dot);
// var kaleidoPass = new THREE.ShaderPass(THREE.KaleidoShader);
// kaleidoPass.uniforms['sides'].value = 3;
// kaleidoPass.uniforms['angle'].value = 45 * Math.PI / 180;
// composer.addPass(kaleidoPass);
// var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
// // mirror.uniforms[ "tDiffuse" ].value = 1.0;
// // mirror.uniforms[ "side" ].value = 3;
// composer.addPass(mirror);
var glitch = new THREE.GlitchPass(64);
glitch.uniforms[ "tDiffuse" ].value = 1.0;
glitch.uniforms[ 'seed' ].value = Math.random() * 5;
glitch.uniforms[ 'byp' ].value = 0;
// glitch.goWild = true;
composer.addPass(glitch);
var superPass = new THREE.ShaderPass(THREE.SuperShader);
superPass.uniforms.vigDarkness.value = 1;
superPass.uniforms.vigOffset.value = 1.3;
superPass.uniforms.glowSize.value = 2;
superPass.uniforms.glowAmount.value = 1;
composer.addPass( superPass );
var tv = new THREE.ShaderPass( THREE.BadTVShader );
tv.uniforms[ "distortion" ].value = 1;
tv.uniforms[ "distortion2" ].value = .01;
// tv.uniforms[ "time" ].value = 1.5;
tv.uniforms[ "speed" ].value = 8.8;
tv.uniforms[ "rollSpeed" ].value = 0.8;
composer.addPass(tv);
var staticPass = new THREE.ShaderPass( THREE.StaticShader );
staticPass.uniforms[ "amount" ].value = 0.15;
staticPass.uniforms[ "size" ].value = 1.0;
staticPass.uniforms[ "time" ].value = 4.5;
composer.addPass(staticPass);
var effect1 = new THREE.ShaderPass(THREE.RGBShiftShader);
effect1.uniforms['amount'].value = 0.003;
effect1.renderToScreen = true;
composer.addPass(effect1);
function turnOnMirror() {
var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
mirror.renderToScreen = true;
composer.addPass(mirror);
}
function turnOffMirror() {
var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
mirror.renderToScreen = false;
composer.addPass(mirror);
}
// add a timer
clock = new THREE.Clock;
/* ==================== [ Stats ] ==================== */
// stats = new Stats();
// stats.domElement.style.position = 'absolute';
// stats.domElement.style.left = '0px';
// stats.domElement.style.top = '0px';
// document.body.appendChild(stats.domElement);
// document.body.appendChild( renderer.domElement );
/* ==================== [ Shapes ] ==================== */
var quantity = 40;
var shapes = [];
for (var i = 0; i < quantity; i++) {
if (Math.random() < 0.5) {
var geometry = new THREE.RingGeometry(4, 40, 3);
// geometry.position = 0;
// var geometry = new THREE.RingGeometry( 30, 30, 18);
// camera.position.z = 60;
// var geometry = new THREE.RingGeometry( 20, 150, 18);
// var geometry = new THREE.RingGeometry( 20, 150, 18);
// var geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
}
else {
//var geometry = new THREE.RingGeometry( 4, 40, 3);
// var geometry = new THREE.RingGeometry( 30, 30, 18);
// var geometry = new THREE.RingGeometry( 1, 5, 6 );
// var material = new THREE.MeshBasicMaterial( { color: 0xffff00,
// side: THREE.DoubleSide } );
// var mesh = new THREE.Mesh( geometry, material );
// scene.add( mesh );
}
if (i % 7 === 0) {
var material = new THREE.MeshPhongMaterial({
color: "#ffffff"
});
} else if (i % 2 === 0) {
var material = new THREE.MeshPhongMaterial({
color: "#666666"
});
} else {
var material = new THREE.MeshPhongMaterial({
color: "#333333"
});
}
var mesh = new THREE.Mesh(geometry, material);
mesh.position.z = -i * 3;
// mesh.rotation.z = i;
shapes.push(mesh);
scene.add(mesh);
}
// function refRate() {
// curTime = Date.now();
// delta = curTime - oldTime;
//
// if (delta > interval) {
// oldTime = curTime - (delta % interval);
// updateSize();
// }
//
// }
// Variables
var u_time = 0;
/* ==================== [ Render Function ] ==================== */
var render = function () {
requestAnimationFrame(render);
// var timer = Date.now() * 0.0010;
// camera.lookAt(scene.position);
u_time++;
for (var i = 0; i < quantity; i++) {
// Set rotation change of shapes
shapes[i].position.z += 0.2;
shapes[i].rotation.z += 0;
shapes[i].scale.x = 1 + Math.sin(i + u_time * 0.1) * 0.05;
shapes[i].scale.y = 1 + Math.sin(i + u_time * 0.1) * 0.05;
// shapes[i].scale.y = 120 + Math.tan(i + u_time * 5.0) * 0.5;
// shapes[i].scale.x = 120 + Math.tan(i + u_time * 5.0) * 0.5;
var change = 1.5 + Math.sin(u_time * 0.5) * 0.5;
// Set wireframe & width
if (Math.random() < change) {
shapes[i].material.wireframe = false;
shapes[i].material.wireframeLinewidth = Math.random() * 2;
// if (shapes[i] / 2 === 0) {
// turnOnMirror();
// }
}
else {
shapes[i].material.wireframe = false;
}
if (shapes[i].position.z > 10) {
shapes[i].position.z = -70;
shapes[i].rotation.z = i;
}
}
// Set Point light Intensity & Position
pointLight.intensity = Math.abs(Math.sin(u_time * 0.2) * 2);
pointLight2.intensity = Math.abs(Math.cos(u_time * 0.2) * 2);
pointLight.position.z = Math.abs(Math.sin(u_time * 0.02) * 30);
pointLight2.position.z = Math.abs(Math.cos(u_time * 0.02) * 30);
renderer.render(scene, camera);
composer.render();
var pCount = particleCount;
while (pCount--) {
var camz = getCamera().position.z;
var particle = particles.vertices[pCount];
particle.y = Math.random() * 500 - 250;
//particleSystem.vertices[i].z = camz + Math.random()*600 + 200 ;
particleSystem.geometry.vertices.needsUpdate = true;
}
particleSystem.rotation.y += -0.001;
particleSystem.rotation.z += 0.005;
var normLevel = 0.2;
beamGroup.rotation.x += BEAM_ROT_SPEED;
beamGroup.rotation.y += BEAM_ROT_SPEED;
beamMaterial.opacity = Math.min(normLevel * 0.4, 0.6);
camera.rotation.z += 0.003;
if (doShake) {
var maxshake = 60;
var shake = normLevel * maxshake ;
camera.position.x = Math.random()*shake - shake/2;
camera.position.y = Math.random()*shake - shake/2;
}
camera.rotation.z += 0.003;
// camera.rotation.y += 0.005;
// camera.rotation.x -= 0.003;
//camera.rotation.z += 0.03;
if (doStrobe){
strobeOn = !strobeOn;
if (strobeOn){
light2.intensity = 2;
}
else {
light2.intensity = 0.5;
}
}
else {
light2.intensity = 0.2;
}
// flash background on level threshold
if (normLevel > 0.5 ){
renderer.setClearColor ( 0xFFFFFF );
backMesh2.visible = true;
}
else{
renderer.setClearColor ( 0x000000 );
backMesh2.visible = false;
}
// show stripes for 6 frames on beat
backMesh2.visible = beatTime < 6;
for(var i = 0; i < BOX_COUNT; i++) {
boxes[i].update();
}
if (audioSrc.context.currentTime > 32) {
turnOnMirror();
}
// console.log(audioSrc.context.currentTime);
}
render();

Three.js getObjectByName delivers undefined

I started my first Three.js project. A solar system which you can see here.
I have a function addCelestrialObject() where I create the planets and I want this function to automatically create the orbit circles what it does for the planets but I want it also for moons.
So every Planet (mesh) becomes a name and I want to access this object to get its center position so I can add a circle to this position if I have a moon.
My problem is that the function scene.getObjectByName(parent,true); always delivers an undefined. You can see the console.log(scene) on my example when you inspect the site.
function addCelestrialObject(name, type, parent, surface, bump, specular,
positionX, positionY, positionZ, size, clouds, drawcircle
) {
var loader = new THREE.TextureLoader();
var group = new THREE.Group();
loader.load(surface, function (texture) {
var geometry = new THREE.SphereGeometry(size, 32, 32);
if (type == "sun") {
var material = new THREE.MeshBasicMaterial({ map: texture });
material.shading = true;
} else {
var material = new THREE.MeshPhongMaterial({ map: texture, overdraw: 0.5 });
material.shading = true;
if (bump) {
material.bumpMap = THREE.ImageUtils.loadTexture(bump);
material.bumpScale = 0.5;
}
if (specular) {
material.specularMap = THREE.ImageUtils.loadTexture(specular);
material.specular = new THREE.Color(0x222222);
}
}
var mesh = new THREE.Mesh(geometry, material);
mesh.name = name;
mesh.position.x = positionX;
mesh.position.y = positionY;
mesh.position.z = positionZ;
objectControls.add(mesh);
mesh.select = function () {
var position = { x: controls.target.x, y: controls.target.y, z: controls.target.z };
var target = { x: this.position.x, y: this.position.y, z: this.position.z };
var tween = new TWEEN.Tween(position).to(target, 500);
tween.easing(TWEEN.Easing.Exponential.InOut)
tween.onUpdate(function () {
controls.target.x = position.x;
controls.target.y = position.y;
controls.target.z = position.z;
controls.dollyIn(2);
});
tween.start();
controls.minDistance = size * 5;
}
onRenderFcts.push(function (delta, now) {
mesh.rotateY(1 / 32 * delta)
});
group.add(mesh);
});
if (clouds == true) {
var canvasResult = document.createElement('canvas')
canvasResult.width = 1024
canvasResult.height = 512
var contextResult = canvasResult.getContext('2d')
// load earthcloudmap
var imageMap = new Image();
imageMap.addEventListener("load", function () {
// create dataMap ImageData for earthcloudmap
var canvasMap = document.createElement('canvas')
canvasMap.width = imageMap.width
canvasMap.height = imageMap.height
var contextMap = canvasMap.getContext('2d')
contextMap.drawImage(imageMap, 0, 0)
var dataMap = contextMap.getImageData(0, 0, canvasMap.width, canvasMap.height)
// load earthcloudmaptrans
var imageTrans = new Image();
imageTrans.addEventListener("load", function () {
// create dataTrans ImageData for earthcloudmaptrans
var canvasTrans = document.createElement('canvas')
canvasTrans.width = imageTrans.width
canvasTrans.height = imageTrans.height
var contextTrans = canvasTrans.getContext('2d')
contextTrans.drawImage(imageTrans, 0, 0)
var dataTrans = contextTrans.getImageData(0, 0, canvasTrans.width, canvasTrans.height)
// merge dataMap + dataTrans into dataResult
var dataResult = contextMap.createImageData(canvasMap.width, canvasMap.height)
for (var y = 0, offset = 0; y < imageMap.height; y++) {
for (var x = 0; x < imageMap.width; x++, offset += 4) {
dataResult.data[offset + 0] = dataMap.data[offset + 0]
dataResult.data[offset + 1] = dataMap.data[offset + 1]
dataResult.data[offset + 2] = dataMap.data[offset + 2]
dataResult.data[offset + 3] = 255 - dataTrans.data[offset + 0]
}
}
// update texture with result
contextResult.putImageData(dataResult, 0, 0)
material.map.needsUpdate = true;
})
imageTrans.src = 'textures/earthcloudmaptrans.jpg';
}, false);
imageMap.src = 'textures/earthcloudmap.jpg';
var geometry = new THREE.SphereGeometry(size + 0.5, 32, 32)
var material = new THREE.MeshPhongMaterial({
map: new THREE.Texture(canvasResult),
side: THREE.DoubleSide,
transparent: true,
opacity: 1,
shading: true,
})
var cloudMesh = new THREE.Mesh(geometry, material);
cloudMesh.position.x = positionX;
cloudMesh.position.y = positionY;
cloudMesh.position.z = positionZ;
group.add(cloudMesh);
onRenderFcts.push(function (delta, now) {
cloudMesh.rotateY(1 / 16 * delta)
});
}
if (drawcircle == true) {
//circle
var radius = Math.abs(distance(0, positionX, 0, positionZ));
segments = 64;
materialLine = new THREE.LineBasicMaterial({ color: 0x00a8ff });
geometry = new THREE.CircleGeometry(radius, segments);
// Remove center vertex
geometry.vertices.shift();
circle = new THREE.Line(geometry, materialLine);
circle.rotation.x = 1.571;
if (parent) {
var object = scene.getObjectByName(parent, true);
//circle.position.x=object.position.x;
//circle.position.y=object.position.y;
//circle.position.z=object.position.z;
}
group.add(circle);
}
scene.add(group);
}

Cannon.JS make walls solid

I am making a go of three.js and cannon.js, but am stuck with being able to make walls solid, or anything solid that doesn't move and does hold the player back.
http://www.trepaning.com/3js/SEA3d/elvisCollideWalls.html
Here is the code I have thus far. Any insight appreciated. I prefer figuring stuff out on my own, but this one thing of making walls solid is holding me back at the moment, and I appreciate any info to get me over this hump.
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var initScene;
var MARGIN = 10;
var MARGINSIDE = 0;
var WIDTH = window.innerWidth || ( 2 + 2 * MARGINSIDE );
//var WIDTH = window.innerWidth/3 || ( 2 + 2 * MARGINSIDE );
//var HEIGHT = window.innerHeight/3 || ( 2 + 2 * MARGIN );
var HEIGHT = window.innerHeight || ( 2 + 2 * MARGIN );
var SCREEN_WIDTH = WIDTH -2 * MARGINSIDE;
var SCREEN_HEIGHT = HEIGHT -2 * MARGIN;
var FAR = 10000;
var DAY = 0;
var stats, camera, scene, renderer;
var mesh, geometry;
var sunLight, pointLight, ambientLight, hemiLight;
var parameters
var clock = new THREE.Clock();
var inRender = true;
var inResize = false;
// cannon physics
var world;
var worldScale = 100;
var timeStep = 1/60;
var walls=[], balls=[], ballMeshes=[], boxes=[], boxMeshes=[];
var solidMaterial;
var playerMaterialPhy;
var playerRigid;
var playerPhysicsMesh;
var UNITSIZE = 250
var WALLHEIGHT = UNITSIZE / 3;
var map = [ // 1 2 3 4 5 6 7 8 9
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1,], // 0
[1, 1, 0, 0, 0, 0, 0, 1, 1, 1,], // 1
[1, 1, 0, 0, 2, 0, 0, 0, 0, 1,], // 2
[1, 0, 0, 1, 0, 2, 0, 0, 0, 1,], // 3
[1, 0, 0, 2, 0, 0, 2, 1, 0, 1,], // 4
[1, 0, 0, 0, 2, 0, 0, 0, 0, 1,], // 5
[1, 1, 1, 0, 0, 0, 0, 0, 1, 1,], // 6
[1, 1, 1, 0, 0, 0, 0, 0, 1, 1,], // 7
[1, 1, 1, 1, 1, 1, 0, 0, 1, 1,], // 8
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1,], // 9
], mapW = map.length, mapH = map[0].length;
// player
var loader;
var player;
var playerMaterial;
var playerMap = { map:undefined, normal:undefined};
var players=[];
var playerName = "LegoElvis";
var scaleFactor = 5;
var velocity = {x : 0, z : 0};
var playerControls = {
moveForward: false,
moveBackward: false,
moveLeft: false,
moveRight: false,
bodyOrientation: 0,
maxSpeed: 275,
maxReverseSpeed: -275,
frontAcceleration: 600,
backAcceleration: 600,
frontDecceleration: 600,
angularSpeed: 2.5,
speed: 0
};
var shadowConfig = {
Visible: false,
Near: 750,
Far: 4000,
Fov: 75,
Bias: -0.0002,
Darkness: 0.5,
Resolution:1024
};
var playerConfig = {
name: "",
loading: 0,
scale: 1,
CloneNumber: 30,
Clone: false
};
var LightConfig = {
Ambient: 0x554b3b,
Fog : 0x00283f
};
var MaterialConfig = {
shininess : 0,
specular: 1,
normalScaleX: 0,
normalScaleY: 0,
bias:0,
bumpScale: 2,
metal:false
};
var sky;
var skyCubeNight, skyCubeDay;
var skyShader;
initScene = function () {
// RENDERER
renderer = new THREE.WebGLRenderer( { clearColor: LightConfig.Fog, clearAlpha: 1, antialias: true } );
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
renderer.setClearColor( LightConfig.Fog, 1 );
renderer.domElement.style.position = "absolute";
document.getElementById( 'viewport' ).appendChild( renderer.domElement );
renderer.shadowMapEnabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.physicallyBasedShading = true;
// SCENE
scene = new THREE.Scene();
scene.fog = new THREE.Fog( LightConfig.Fog , 1000, FAR );
// CAMERA
camera = new THREE.PerspectiveCamera( 45, SCREEN_WIDTH / SCREEN_HEIGHT, 2, FAR );
camera.position.set( 50, 300, 350 );
// CAMERA CONTROL
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.center.set( 0, 0, 0 );
controls.keys = [];
controls.maxPolarAngle = toRad(90);
controls.userRotateSpeed = 1.8;
controls.zoomSpeed = 1.6;
controls.userPanSpeed = 0.8;
// GROUND
var mapGround = THREE.ImageUtils.loadTexture( "images/legoElvis.jpg" );
mapGround.anisotropy = renderer.getMaxAnisotropy();
mapGround.repeat.set( 100, 100 );
mapGround.wrapS = mapGround.wrapT = THREE.RepeatWrapping;
mapGround.magFilter = THREE.NearestFilter;
mapGround.format = THREE.RGBFormat;
var groundMaterial = new THREE.MeshPhongMaterial( { shininess: 10, ambient: 0x444444, color: 0xffffff, specular: 0xffffff, map: mapGround, metal: false } );
var planeGeometry = new THREE.PlaneGeometry( 100, 100 );
var ground = new THREE.Mesh( planeGeometry, groundMaterial );
ground.position.set( 0, 0, 0 );
ground.rotation.x = - Math.PI / 2;
ground.scale.set( 1000, 1000, 1000 );
ground.receiveShadow = true;
scene.add( ground );
initLights();
initPhysics();
loadSea3dModel();
stats = new Stats();
document.getElementById('my-stat').appendChild(stats.domElement);
// LISTENERS
window.addEventListener( 'resize', onWindowResize, false );
document.addEventListener( 'keydown', onKeyDown, false );
document.addEventListener( 'keyup', onKeyUp, false );
// TWEEN
parameters = { control: 0 };
animate();
}
//-----------------------------------------------------
// LIGHT
//-----------------------------------------------------
function initLights() {
var sunIntensity = 0.8;
var pointIntensity = 0.3;
var pointColor = 0xffffff;
var skyIntensity = 1;
ambientLight = new THREE.AmbientLight( LightConfig.Ambient );
scene.add( ambientLight );
hemiLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.6 );
hemiLight.color.setHSL( 0.63, 0.05, 0 );
hemiLight.groundColor.setHex( 0xe4c8a0 );
hemiLight.position.set( 0, 400, 0 );
scene.add( hemiLight );
pointLight = new THREE.PointLight( LightConfig.Moon, pointIntensity, 5000 );
pointLight.position.set( -1000, 0, -1000 );
scene.add( pointLight );
sunLight = new THREE.SpotLight( LightConfig.Sun, sunIntensity, 0, Math.PI/2, 1 );
sunLight.position.set( 1000, 2000, 1000 );
sunLight.castShadow = true;
sunLight.shadowCameraVisible = shadowConfig.Visible;
sunLight.shadowCameraNear = shadowConfig.Near;
sunLight.shadowCameraFar = shadowConfig.Far;
sunLight.shadowCameraFov = shadowConfig.Fov;
sunLight.shadowBias = shadowConfig.Bias;
sunLight.shadowDarkness = shadowConfig.Darkness * sunIntensity;
sunLight.shadowMapWidth = shadowConfig.Resolution;
sunLight.shadowMapHeight = shadowConfig.Resolution;
scene.add( sunLight );
}
function enableCascadeShadow() {
renderer.shadowMapCascade = true;
sunLight.shadowCascade = true;
sunLight.shadowCascadeCount = 3;
sunLight.shadowCascadeNearZ = [ -1.000, 0.995, 0.998 ];
sunLight.shadowCascadeFarZ = [ 0.995, 0.998, 1.000 ];
sunLight.shadowCascadeWidth = [ shadowConfig.Resolution, shadowConfig.Resolution, shadowConfig.Resolution ];
sunLight.shadowCascadeHeight = [ shadowConfig.Resolution, shadowConfig.Resolution, shadowConfig.Resolution ];
}
//-----------------------------------------------------
// RESIZE
//-----------------------------------------------------
function onWindowResize( event ) {
inResize = true;
//document.getElementById("viewport").style.background = '#222222';
SCREEN_WIDTH = window.innerWidth - 2 * MARGINSIDE;
SCREEN_HEIGHT = window.innerHeight - 2 * MARGIN;
camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
camera.updateProjectionMatrix();
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
}
//-----------------------------------------------------
// KEYBOARD
//-----------------------------------------------------
function onKeyDown ( event ) {
switch ( event.keyCode ) {
case 38: /*up*/
case 87: /*W*/
case 90: /*Z*/ playerControls.moveForward = true; break;
case 40: /*down*/
case 83: /*S*/ playerControls.moveBackward = true; break;
case 37: /*left*/
case 65: /*A*/
case 81: /*Q*/ playerControls.moveLeft = true; break;
case 39: /*right*/
case 68: /*D*/ playerControls.moveRight = true; break;
}
}
function onKeyUp ( event ) {
switch( event.keyCode ) {
case 38: /*up*/
case 87: /*W*/
case 90: /*Z*/ playerControls.moveForward = false; break;
case 40: /*down*/
case 83: /*S*/ playerControls.moveBackward = false; break;
case 37: /*left*/
case 65: /*A*/
case 81: /*Q*/ playerControls.moveLeft = false; break;
case 39: /*right*/
case 68: /*D*/ playerControls.moveRight = false; break;
}
};
//-----------------------------------------------------
// SEA3D
//-----------------------------------------------------
function loadSea3dModel() {
loader = new THREE.SEA3D( false );
//loader.matrixAutoUpdate = true;
//loader.invertCamera = true;
loader.onComplete = function( e ) {
player = loader.getMesh(playerName);
player.play("idle");
player.scale.set( playerConfig.scale*3, playerConfig.scale*3, -playerConfig.scale*3 );
scene.add( player );
creatPlayerPhysics();
};
//loader.load( 'folder/'+playerName+'.sea' );
loader.load( 'models/legoElvis.sea' );
}
// PLAYER ANIMATION
function updatePlayer(delta) {
if (playerControls.moveForward){
if (player.currentAnimation.name == "idle") player.play("walk");
} else if (playerControls.moveBackward){
if (player.currentAnimation.name == "idle") player.play("walk");
}
else {
if(player.currentAnimation.name == "walk") player.play("idle");
}
THREE.AnimationHandler.update( delta );
updatePlayerMove(delta);
}
// PLAYER MOVE
function updatePlayerMove( delta ) {
playerControls.maxReverseSpeed = -playerControls.maxSpeed;
if ( playerControls.moveForward ) playerControls.speed = THREE.Math.clamp( playerControls.speed + delta * playerControls.frontAcceleration, playerControls.maxReverseSpeed, playerControls.maxSpeed );
if ( playerControls.moveBackward ) playerControls.speed = THREE.Math.clamp( playerControls.speed - delta * playerControls.backAcceleration, playerControls.maxReverseSpeed, playerControls.maxSpeed );
// orientation based on controls
// (don't just stand while turning)
var dir = 1;
if ( playerControls.moveLeft ) {
playerControls.bodyOrientation += delta * playerControls.angularSpeed;
playerControls.speed = THREE.Math.clamp( playerControls.speed + dir * delta * playerControls.frontAcceleration, playerControls.maxReverseSpeed, playerControls.maxSpeed );
}
if ( playerControls.moveRight ) {
playerControls.bodyOrientation -= delta * playerControls.angularSpeed;
playerControls.speed = THREE.Math.clamp( playerControls.speed + dir * delta * playerControls.frontAcceleration, playerControls.maxReverseSpeed, playerControls.maxSpeed );
}
// speed decay
if ( ! ( playerControls.moveForward || playerControls.moveBackward ) ) {
if ( playerControls.speed > 0 ) {
var k = exponentialEaseOut( playerControls.speed / playerControls.maxSpeed );
playerControls.speed = THREE.Math.clamp( playerControls.speed - k * delta * playerControls.frontDecceleration, 0, playerControls.maxSpeed );
} else {
var k = exponentialEaseOut( playerControls.speed / playerControls.maxReverseSpeed );
playerControls.speed = THREE.Math.clamp( playerControls.speed + k * delta * playerControls.backAcceleration, playerControls.maxReverseSpeed, 0 );
}
}
// displacement
var forwardDelta = playerControls.speed * delta;
velocity.x = Math.sin( playerControls.bodyOrientation ) * forwardDelta;
velocity.z = Math.cos( playerControls.bodyOrientation ) * forwardDelta;
player.position.x += velocity.x;
player.position.z += velocity.z;
player.position.y = playerConfig.scale*scaleFactor;
// steering
player.rotation.y = playerControls.bodyOrientation;
if(controls){
//controls.target.set( player.position.x, player.position.y, player.position.z );
camera.position.x += velocity.x;
camera.position.z += velocity.z;
controls.center.set( player.position.x, player.position.y, player.position.z );
}
if(playerRigid){
//playerRigid.position.set(player.position.x, player.position.y+3, player.position.z );
playerRigid.position.set(player.position.x, player.position.y+80, player.position.z+15 );
playerRigid.quaternion.setFromAxisAngle(new CANNON.Vec3(0,1,0),player.rotation.y);
}
};
function exponentialEaseOut( k ) { return k === 1 ? 1 : - Math.pow( 2, - 10 * k ) + 1; };
//-----------------------------------------------------
// RENDER LOOP
//-----------------------------------------------------
function animate() {
requestAnimationFrame( animate );
if(inRender || inResize){
//if(isPad)PadTest();
//updateCamera();
var delta = clock.getDelta();
if(player!=null)updatePlayer(delta);
updatePhysics();
render();
stats.update();
}
inResize = false;
}
function render() {
TWEEN.update();
controls.update();
scene.fog.color.setHSL( 0.63, 0.05, parameters.control );
renderer.setClearColor( scene.fog.color, 1 );
pointLight.intensity = - parameters.control * 0.5 + 1;
hemiLight.color.setHSL( 0.63, 0.05, parameters.control )
sunLight.shadowDarkness = shadowConfig.Darkness * sunLight.intensity;
renderer.render( scene, camera );
}
function tell(s){
document.getElementById("debug").innerHTML = s;
}
//-----------------------------------------------------
// PHYSICS
//-----------------------------------------------------
function initPhysics() {
world = new CANNON.World();
world.quatNormalizeSkip = 0;
world.quatNormalizeFast = false;
var solver = new CANNON.GSSolver();
world.defaultContactMaterial.contactEquationStiffness = 1e9;
world.defaultContactMaterial.contactEquationRegularizationTime = 4;
solver.iterations = 3;
solver.tolerance = 0.1;
world.gravity.set(0,-9.82*worldScale,0);//world.gravity.set(0,-9.82,0); // m/s²
world.broadphase = new CANNON.NaiveBroadphase();
// Create a slippery material (friction coefficient = 0.0)
physicsMaterial = new CANNON.Material("slipperyMaterial");
solidMaterial = new CANNON.Material("solidMaterial");
playerMaterialPhy = new CANNON.Material("playerMat");
var physicsContactMaterial = new CANNON.ContactMaterial(physicsMaterial, physicsMaterial, 0.0, 0.3 );
var playerContactMaterial = new CANNON.ContactMaterial(playerMaterialPhy, playerMaterialPhy, 0.0, 0.3 );
var solidContactMaterial = new CANNON.ContactMaterial(solidMaterial, solidMaterial, 0.2, 0.6 );
world.addContactMaterial(physicsContactMaterial);
world.addContactMaterial(playerContactMaterial);
world.addContactMaterial(solidContactMaterial);
// Create infinie plane
var groundShape = new CANNON.Plane();
var groundBody = new CANNON.RigidBody(0,groundShape,physicsMaterial);
groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0),-Math.PI/2);
world.add(groundBody);
createBoxeObject();
createBallObject();
}
function creatPlayerPhysics() {
if(playerPhysicsMesh){
scene.remove(playerPhysicsMesh);
playerPhysicsMesh.geometry.dispose();
}
if(playerRigid)world.remove(playerRigid);
//player body
var halfExtents = new CANNON.Vec3(0.5*worldScale,playerConfig.scale*80, 0.25*worldScale);
var playerShape = new CANNON.Box(halfExtents);
playerRigid = new CANNON.RigidBody(0,playerShape, playerMaterialPhy);
world.add(playerRigid);
playerRigid.linearDamping=0.01;
playerRigid.angularDamping=0.01;
var boxGeometry = new THREE.CubeGeometry(halfExtents.x*2,halfExtents.y*2,halfExtents.z*2);
playerPhysicsMesh = new THREE.Mesh( boxGeometry );
scene.add(playerPhysicsMesh);
playerPhysicsMesh.useQuaternion = true;
playerPhysicsMesh.castShadow = false;
playerPhysicsMesh.receiveShadow = false;
showPlayerPhysics();
}
function showPlayerPhysics() {
//if(OptionConfig.ShowPlayerHitBox)playerPhysicsMesh.visible = true;
//else playerPhysicsMesh.visible = true;
playerPhysicsMesh.visible = true;
}
function createBallObject() {
var s = worldScale;
var mat = new THREE.MeshLambertMaterial( { color: 0xdddddd } );
var radius;
var mass = 4;
var sphereShape;
for(var i=0; i<5; i++){
radius = (0.2+(Math.random()*0.8))*s;
sphereShape = new CANNON.Sphere(radius);
ballGeometry = new THREE.SphereGeometry(radius, 32, 32 );
var sphereBody = new CANNON.RigidBody(mass,sphereShape,physicsMaterial);
//sphereBody.linearDamping = 0.9;
var x = ((Math.random()-0.5)*20)*s;
var y = (1 + (Math.random()-0.5)*1)*s;
var z = ((Math.random()-0.5)*20)*s;
sphereBody.position.set(x,y,z);
sphereBody.linearDamping=0.03;
sphereBody.angularDamping=0.03;
world.add(sphereBody);
var ballMesh = new THREE.Mesh( ballGeometry, mat );
scene.add(ballMesh);
ballMesh.useQuaternion = true;
ballMesh.castShadow = true;
ballMesh.receiveShadow = true;
// add to array
balls.push(sphereBody);
ballMeshes.push(ballMesh);
}
}
function createBoxeObject() {
var s = worldScale;
var material = new THREE.MeshLambertMaterial( { color: 0x222222 } );
// Add boxes
var sx, xy, xz;
var halfExtents = new CANNON.Vec3(1*s,1*s,1*s);
var boxShape = new CANNON.Box(halfExtents);
var boxGeometry = new THREE.CubeGeometry(halfExtents.x*2,halfExtents.y*2,halfExtents.z*2);
for(var i=0; i<5; i++){
sx= 0.2+(Math.random()*0.8);
sy= 0.2+(Math.random()*0.8);
sz= 0.2+(Math.random()*0.8);
halfExtents = new CANNON.Vec3(sx*s,sy*s,sz*s);
boxShape = new CANNON.Box(halfExtents);
boxGeometry = new THREE.CubeGeometry(halfExtents.x*2,halfExtents.y*2,halfExtents.z*2);
var x = ((Math.random()-0.5)*20)*s;
var y = (1 + (Math.random()-0.5)*1)*s;
var z = ((Math.random()-0.5)*20)*s;
var boxBody = new CANNON.RigidBody(9,boxShape, solidMaterial);
var boxMesh = new THREE.Mesh( boxGeometry, material );
world.add(boxBody);
scene.add(boxMesh);
boxBody.position.set(x,y,z);
//boxMesh.position.set(x,y,z);
boxBody.quaternion.setFromAxisAngle(new CANNON.Vec3(0,0,0),toRad(Math.random()*360));
boxMesh.castShadow = true;
boxMesh.receiveShadow = true;
boxMesh.useQuaternion = true;
boxes.push(boxBody);
boxMeshes.push(boxMesh);
}
function createObstacle() {
obstacleMesh = new THREE.CubeGeometry(150, 50, 50)
obstacleMaterial = new THREE.MeshLambertMaterial( { color: 0x666666 } );
obstacleObject = new THREE.Mesh(obstacleMesh, obstacleMaterial);
obstacleObject.position.set(0, 26, 200);
obstacleObject.castShadow = true;
obstacleObject.receiveShadow = true;
scene.add(obstacleObject);
}
createObstacle();
function setupScene() {
var units = mapW;
// Geometry: walls
var cube = new THREE.CubeGeometry(UNITSIZE, WALLHEIGHT, UNITSIZE);
var materials = [
new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture('images/legoElvisR.jpg')}), //wall 1
new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture('images/legoElvisG.jpg')}), //wall 2
];
for (var i = 0; i < mapW; i++) {
for (var j = 0, m = map[i].length; j < m; j++) {
if (map[i][j]) {
var wall = new THREE.Mesh(cube, materials[map[i][j]-1]);
wall.position.x = (i - units/2) * UNITSIZE;
wall.position.y = WALLHEIGHT/2;
wall.position.z = (j - units/2) * UNITSIZE;
wall.castShadow = true;
wall.receiveShadow = true;
scene.add(wall);
}
}
}
}
setupScene();
// Add linked boxes
var size = 0.5*s;
var he = new CANNON.Vec3(size,size,size*0.1);
var boxShape = new CANNON.Box(he);
var mass = 0;
var space = 0.1*size;
var N=5, last;
var boxGeometry = new THREE.CubeGeometry(he.x*2,he.y*2,he.z*2);
for(var i=0; i<N; i++){
var boxbody = new CANNON.RigidBody(mass,boxShape, solidMaterial);
var boxMesh = new THREE.Mesh( boxGeometry, material );
boxbody.position.set(5*s,((N-i)*(size*2+2*space) + size*2+space)-150,0);
boxbody.linearDamping=0.01;
boxbody.angularDamping=0.01;
boxMesh.useQuaternion = true;
boxMesh.castShadow = true;
boxMesh.receiveShadow = true;
world.add(boxbody);
scene.add(boxMesh);
boxes.push(boxbody);
boxMeshes.push(boxMesh);
if(i!=0){
// Connect this body to the last one
var c1 = new CANNON.PointToPointConstraint(boxbody,new CANNON.Vec3(-size,size+space,0),last,new CANNON.Vec3(-size,-size-space,0));
var c2 = new CANNON.PointToPointConstraint(boxbody,new CANNON.Vec3(size,size+space,0),last,new CANNON.Vec3(size,-size-space,0));
world.addConstraint(c1);
world.addConstraint(c2);
} else {
mass=0.3;
}
last = boxbody;
}
}
function updatePhysics() {
if(!world) return;
world.step(timeStep);
// update player mesh test
if(playerRigid !== undefined){
playerRigid.position.copy(playerPhysicsMesh.position);
playerRigid.quaternion.copy(playerPhysicsMesh.quaternion);
}
// Update ball positions
for(var i=0; i<balls.length; i++){
balls[i].position.copy(ballMeshes[i].position);
balls[i].quaternion.copy(ballMeshes[i].quaternion);
}
// Update box positions
for(var i=0; i<boxes.length; i++){
boxes[i].position.copy(boxMeshes[i].position);
boxes[i].quaternion.copy(boxMeshes[i].quaternion);
}
}
//-----------------------------------------------------
// MATH
//-----------------------------------------------------
function toRad(Value) {
return Value * Math.PI / 180;
}
window.onload = initScene;
When you update your physics in updatePlayerMove, you set the position of the corresponding Cannon.js body. This body will never have a chance to update its position by itself since you override its position all the time.
Setting the position of bodies like this makes the physics unstable. You'll get large and buggy overlaps. And, of course, the player will be able to walk through walls.
Try controlling the player body via velocity instead. Cannon.js will then provide the response on the player for you, and the physics will become stable:
playerRigid.velocity.set(vx,vy,vz);

How to solve this loop and present the cones in an order?

var lc_relationship= null;
var container, nSize = 100;
var camera, scene, renderer;
var scale = 10, scale1 = 100; N=50, cubeRotSpd=0;
var arr= [];
var width = window.innerWidth, height = window.innerHeight;
function generateData()
{
var aSensor1 = [],
aSensor2 = [],
aSensor3 = [];
lc_relationship = {
"sensor1":[],
"sensor2":[],
"sensor3":[]
}
for(i=1; i<=nSize; i++)
{
aSensor1.push(i);
aSensor2.push(i);
aSensor3.push(i);
}
for(n=0; n<nSize; n++)
{
var pos1 = Math.floor(Math.random() * (nSize-n));
var pos2 = Math.floor(Math.random() * (nSize-n));
var pos3 = Math.floor(Math.random() * (nSize-n));
var int1 = aSensor1[pos1]; aSensor1.splice(pos1,1);
var int2 = aSensor2[pos2]; aSensor2.splice(pos2,1);
var int3 = aSensor3[pos3]; aSensor3.splice(pos3,1);
lc_relationship.sensor1[int1-1] =
{
"ObjectID" : "sens1_" + rightPad(int1),
"Geometry" : getGeometry(),
"Parent":null,
"child": "sens2_" + rightPad(int2),
"z_cordinate": -5
}
lc_relationship.sensor2[int2-1] =
{
"ObjectID" : "sens2_" + rightPad(int2),
"Geometry" : getGeometry(),
"Parent":"sens1_" + rightPad(int1),
"child": "sens3_" + rightPad(int3),
"z_cordinate": 0
}
lc_relationship.sensor3[int3-1] =
{
"ObjectID" : "sens3_" + rightPad(int3),
"Geometry" : getGeometry(),
"Parent":"sens2_" + rightPad(int2),
"child": null,
"z_cordinate": 5
}
}
}
function rightPad(number)
{
var tmpStr = number.toString();
return ("000" + tmpStr).substring(tmpStr.length, tmpStr.length+3);
}
function getGeometry()
{
var geo = new THREE.Geometry();
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( 0, 0, 0)));
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( -0.5, 0.5, 1)));
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( 0.5, 0.5, 1)));
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( -0.5, -0.5, 1)));
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( 0.5,-0.5, 1)));
geo.faces.push( new THREE.Face3(0,1,2));
geo.faces.push( new THREE.Face3(2,1,4));
geo.faces.push( new THREE.Face3(1,3,4));
geo.faces.push( new THREE.Face3(4,3,0));
geo.faces.push( new THREE.Face3(3,1,0));
geo.faces.push( new THREE.Face3(0,2,4));
geo.computeFaceNormals();
/* cone = new THREE.Mesh(geo, meshMaterial);
cone.doubleSided = true;
cone.overdraw = true;*/
return geo;
}
function posgeo()
{ generateData();
//var jsonText = JSON.stringify(lc_relationship);
//document.getElementById("output").innerHTML=jsonText;
//document.getElementById("test").innerHTML=lc_relationship.sensor1[0].z_cordinate;
init();
animate();
}
function init()
{
container = document.getElementById("output");
camera = new THREE.PerspectiveCamera( 45, width / height, 0.1, 1000 );
camera.position.y = 0;
camera.position.z = 45;
camera.lookAt(new THREE.Vector3(0, 0, 0));
scene = new THREE.Scene();
scene.add(camera);
renderer = new THREE.WebGLRenderer(/*{antialias:true}*/);
renderer.setClearColorHex(0xffffff, 1);
renderer.setSize( width, height );
var meshmaterial = new THREE.MeshLambertMaterial( { color: 0x0000CC, opacity: 0.3, depthWrite: false, depthTest: false });
I'm having whole problem at this loop, Can someone help me to fix this? The Loop is here:
for ( var i = 0; i <nSize; i++)
for ( var j = -5; j < 5; j++)
for ( var k = -5; k < 5; k++)
{
var cone1 = new THREE.MESH(lc_relationship.sensor1[i].Geometry,meshMaterial);
cone1.doubleSided = true;
cone1.overdraw = true;
scene.add(cone1);
var cone2 = new THREE.MESH(lc_relationship.sensor2[i].Geometry,meshMaterial);
cone2.doubleSided = true;
cone2.overdraw = true;
scene.add(cone2);
var cone3 = new THREE.MESH(lc_relationship.sensor3[i].Geometry,meshMaterial);
cone3.doubleSided = true;
cone3.overdraw = true;
scene.add(cone3);
cone1.position.set(2*k, 2*j,lc_relationship.sensor1[i].z_cordinate);
cone2.position.set(2*k, 2*j,lc_relationship.sensor2[i].z_cordinate);
cone3.position.set(2*k, 2*j,lc_relationship.sensor3[i].z_cordinate);
}
All I want to dispay cones like image below :
and the remaining Code:
var light = new THREE.DirectionalLight(0xffffff, 0.6);
light.position.y = 1;
light.position.x = 1;
light.position.z = 1;
scene.add(light);
light = new THREE.DirectionalLight(0xffffff, 0.6);
light.position.y = -1;
light.position.x = -1;
light.position.z = -1;
scene.add(light);
light = new THREE.DirectionalLight(0xffffff, 0.6);
light.position.y = 1;
light.position.x = 0;
light.position.z = 0;
scene.add(light);
container.appendChild( renderer.domElement );
}
function animate()
{
requestAnimationFrame( animate );
render();
}
function render()
{
renderer.render(scene, camera);
}
Can Some help to solve this issue. This task is really sitting on head all the time :(
You can do it with a single loop, by calculating j and k from j instead of adding two more loops:
for ( var i = 0; i <nSize; i++)
{
var k = i%10,
j = (i-k)/10;
j = j*2 - 10; // You may need to adjust this "10",
k = k*2 - 10; // may be "9", so the layers get centered.
//console.log(j,k)
var cone1 = new THREE.MESH(lc_relationship.sensor1[i].Geometry,meshMaterial);
cone1.doubleSided = true;
cone1.overdraw = true;
scene.add(cone1);
var cone2 = new THREE.MESH(lc_relationship.sensor2[i].Geometry,meshMaterial);
cone2.doubleSided = true;
cone2.overdraw = true;
scene.add(cone2);
var cone3 = new THREE.MESH(lc_relationship.sensor3[i].Geometry,meshMaterial);
cone3.doubleSided = true;
cone3.overdraw = true;
scene.add(cone3);
cone1.position.set(j, k, lc_relationship.sensor1[i].z_cordinate);
cone2.position.set(j, k, lc_relationship.sensor2[i].z_cordinate);
cone3.position.set(j, k, lc_relationship.sensor3[i].z_cordinate);
}

Categories