I would like to set object at the end of sphere radius based on object.position.set (x,y,z)
In typical mathematic formula for coordinates of the point on sphere we have:
var x = radius * Math.cos(phi) * Math.cos(theta);
var y = radius * Math.cos(phi) * Math.sin(theta);
var z = radius * Math.cos(phi);
I use
var x = radius * Math.cos(angleZ) * Math.cos(angleX);
var y = radius * Math.cos(angleZ) * Math.sin(angleX);
var z = radius * Math.cos(angleZ);
I know that this is wrong becasue thete and phi are not this angles
How can i connect this 3 angles angleX, angleY, angleZ to transformt it to phi and theta
In Three js i have :
cylinderX.rotation.x = degToRad(angleX);
cylinderX.rotation.y = degToRad(angleY);
cylinderX.rotation.z = degToRad(angleZ);
degToRad - function which change deg to radians
where
angleX is angle between y plane and z plane
angleY is angle between z plane and x plane
angleZ is angle between x plane and y plane
phi and theta are difrrent angles becasue theta is angle between radius and plane
I run animation and position of object ( x,y,z) and itts location on sphere plane is wrong
How can i resolved this problem ?
To be more specific , here below is my code and example:
http://newdesignlive.neomedia.info/index.html
I would like to set this green cube at the end of this red cuboid when car is rotating in all angles on all axis x,y,z
In arrays : x[...], y[...], z[...] you have values of angles how car (object) is rotating on all axis (X, Y, Z);
I do not know how to connect angleX, angleZ, angleY to "phi" and "theta" to set "green cube" on correct position x,y,z depend on radius = 100 for example;
In animate.js here is all code I add it here bellow to
var container, stats, camera, scene, renderer, object;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var angleX=0, angleY=0, angleZ=0, G=0;
var x; var y; var z;
var times = [];
x = ["0", "10", "20","30", "40", "50" ];
y = ["0", "20", "40","60", "70", "80" ];
z = ["0", "30", "60","90", "120", "150" ];
gX = ["1", "1.4", "0.7", "0.4", "1", "1.2", "0.5", "1.2", "1.4", "1.3", "1", "0.7" ];
gY = ["1", "2", "1", "2", "1", "2", "3", "1.2", "1.4", "1.3", "1", "2" ];
gZ = ["1", "2", "1", "2", "1", "2", "3", "1.2", "1.4", "1.3", "1", "2" ];
generateTimesForAngles();
generateTimesForG();
var currentTransform = 0;
var currentStep = 0;
var intervalTime = 20;
var intervalTimeG = 50
setInterval(transformAngleX,intervalTime);
setInterval(transformAngleY,intervalTime);
setInterval(transformAngleZ,intervalTime);
setInterval(transformGX,intervalTimeG);
setInterval(transformGY,intervalTimeG);
setInterval(transformGZ,intervalTimeG);
init();
animate();
function setVectorDirection (position, gValue)
{
var gValue = document.getElementById('g').value;
gValue = gValue*10;
var direction = document.getElementById("VectorDirection");
var position = direction.options[direction.selectedIndex].value;
var darkMaterial = new THREE.MeshBasicMaterial( { color: 0x222222 } );
var wireframeMaterial = new THREE.MeshBasicMaterial( { color: 0x222222, wireframe: true, transparent: true } ); var multiMaterial = [ darkMaterial, wireframeMaterial ];
var x;
var y;
x = 120 + gValue - gValue/2;
y = 110;
}
function init(objectfilename, materialfilename) {
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xDEDEDE, 1 );
container = document.createElement('div');
document.body.appendChild(container);
container.appendChild( renderer.domElement )
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.y = 200;
camera.position.z = 0;
camera.position.x = 400;
controls = new THREE.OrbitControls( camera );
controls.addEventListener( 'change', render );
scene = new THREE.Scene();
var gridHelper = new THREE.GridHelper( 500, 100 );
gridHelper.setColors(0xFFFFFF, 0xFFFFFF);
scene.add(gridHelper);
var material = new THREE.LineBasicMaterial({
color: 0x0000ff
});
var initColor = new THREE.Color( 0xFFFFFF );
var initTexture = THREE.ImageUtils.generateDataTexture( 1, 1, initColor );
var groundMaterial = new THREE.MeshPhongMaterial
(
{
color: 0xEDEDED,
specular: 0xEDEDED,
map: initTexture }
);
var groundTexture = THREE.ImageUtils.loadTexture
(
"red.jpg",
undefined,
function()
{
groundMaterial.map = groundTexture
}
);
groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
groundTexture.repeat.set( 25, 25 );
groundTexture.anisotropy = 16;
var backgroundmesh = new THREE.Mesh( new THREE.PlaneGeometry( 20000, 20000 ), groundMaterial );
backgroundmesh.position.y = -200;
backgroundmesh.rotation.x = - Math.PI / 2;
backgroundmesh.receiveShadow = true;
scene.add( backgroundmesh );
setVectorDirection();
light = new THREE.DirectionalLight(0xffffff);
light.position.set(0, 100, 60);
light.castShadow = true;
light.shadowCameraLeft = -60;
light.shadowCameraTop = -60;
light.shadowCameraRight = 60;
light.shadowCameraBottom = 60;
light.shadowCameraNear = 1;
light.shadowCameraFar = 10000;
light.shadowBias = -.0001
light.shadowMapWidth = light.shadowMapHeight = 1024;
light.shadowDarkness = .7;
scene.add(light);
mesh1 = new THREE.Mesh( geometry, material );
mesh1.position.set(100,100,100);
scene.add( mesh1 );
var geometry;
loader = new THREE.JSONLoader();
var material = new THREE.MeshLambertMaterial({
map: THREE.ImageUtils.loadTexture('gtare.jpg'),
colorAmbient: [0.480000026226044, 0.480000026226044, 0.480000026226044],
colorDiffuse: [0.480000026226044, 0.480000026226044, 0.480000026226044],
colorSpecular: [0.8999999761581421, 0.8999999761581421, 0.8999999761581421]
});
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
grotX = new THREE.Mesh( new THREE.CylinderGeometry( 0.4, 8, 8, 40, 1 ),new THREE.MeshBasicMaterial( { color: 0x458B00 } ));
cylinderX = new THREE.Mesh(new THREE.BoxGeometry(10,10,10)/*THREE.CylinderGeometry(4, 4, 300, 50, 50, false)*/,new THREE.MeshBasicMaterial( { color: 0x458B00 } ));
cylinderY = new THREE.Mesh(new THREE.BoxGeometry(10,10,10/*4, 4, 300, 50, 50, false*/),new THREE.MeshBasicMaterial( { color: 0x01C5BB } ));
cylinderZ = new THREE.Mesh(new THREE.BoxGeometry(10,200,10/*4, 4, 300, 50, 50, false*/),new THREE.MeshBasicMaterial( { color: 0xFF0000 } ));
scene.add(cylinderX);
scene.add(cylinderY);
scene.add(cylinderZ);
loader.load('car.js', function (geometry, materials) {
var material = new THREE.MeshLambertMaterial({
map: THREE.ImageUtils.loadTexture('gtare.jpg'),
colorAmbient: [0.480000026226044, 0.480000026226044, 0.480000026226044],
colorDiffuse: [0.480000026226044, 0.480000026226044, 0.480000026226044],
colorSpecular: [0.8999999761581421, 0.8999999761581421, 0.8999999761581421]
});
mesh = new THREE.Mesh( geometry, material );
mesh.receiveShadow = true;
scene.add(mesh);
render();
});
}
function degToRad(degrees) {
return degrees * Math.PI / 180.0;
}
function radToDeg(radians) {
return parseInt(radians * 180.0 / Math.PI);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}
function generateTimesForAngles() {
var baseTime360 = 10000;
for(i=0;i<z.length-1;i++) {
var timeMiddle = 10000;
times.push(timeMiddle);
}
}
function generateTimesForG() {
var baseTimeallG = 5000;
for(i=0;i<g.length-1;i++) {
var timeMiddleG = 240;
times.push(timeMiddleG);
}
}
function transformGX() {
var steps = times[currentTransform] / intervalTime;
var singleStepGX = (gX[currentTransform+1]-gX[currentTransform]) / steps;
if(currentStep<steps) {
currentStep++;
GX = +gX[currentTransform] + (+currentStep * +singleStepGX);
} else if(currentTransform<times.length){
currentStep = 0;
currentTransform++;
GX = gX[currentTransform];
} else {
}
}
function transformGY() {
var steps = times[currentTransform] / intervalTime;
var singleStepGY = (gY[currentTransform+1]-gY[currentTransform]) / steps;
if(currentStep<steps) {
currentStep++;
GY = +gY[currentTransform] + (+currentStep * +singleStepGY);
} else if(currentTransform<times.length){
currentStep = 0;
currentTransform++;
GY = gY[currentTransform];
} else {
}
}
function transformGZ() {
var steps = times[currentTransform] / intervalTime;
var singleStepGZ = (gZ[currentTransform+1]-gZ[currentTransform]) / steps;
if(currentStep<steps) {
currentStep++;
GZ = +gZ[currentTransform] + (+currentStep * +singleStepGZ); // Pamiętaj o plusach!!!
} else if(currentTransform<times.length){
currentStep = 0;
currentTransform++;
GZ = gZ[currentTransform];
} else {
}
}
function transformAngleX() {
var steps = times[currentTransform] / intervalTime;
var singleStepAngle = (x[currentTransform+1]-x[currentTransform]) / steps;
if(currentStep<steps) {
currentStep++;
angleX = +x[currentTransform] + (+currentStep * +singleStepAngle);
} else if(currentTransform<times.length){
currentStep = 0;
currentTransform++;
angleX = x[currentTransform];
} else {
}
}
function transformAngleY() {
var steps = times[currentTransform] / intervalTime;
var singleStepAngle = (y[currentTransform+1]-y[currentTransform]) / steps;
if(currentStep<steps) {
currentStep++;
angleY = +y[currentTransform] + (+currentStep * +singleStepAngle);
} else if(currentTransform<times.length){
currentStep = 0;
currentTransform++;
angleY = y[currentTransform];
} else {
}
}
function transformAngleZ() {
var steps = times[currentTransform] / intervalTime;
var singleStepAngle = (z[currentTransform+1]-z[currentTransform]) / steps;
if(currentStep<steps) {
currentStep++;
angleZ = +z[currentTransform] + (+currentStep * +singleStepAngle); // Pamiętaj o plusach!!!
} else if(currentTransform<times.length){
currentStep = 0;
currentTransform++;
angleZ = z[currentTransform];
} else {
}
}
var i = 0;
function animate() {
i++;
requestAnimationFrame( animate );
var x = 100 * Math.sin(degToRad(angleX))* Math.cos(degToRad(angleY));
var y = 100 * Math.sin(degToRad(angleX))* Math.sin(degToRad(angleY));
var z = 100 * Math.cos(degToRad(angleX));
z = -z;
cylinderX.position.set(x,y,z);
cylinderY.position.set(0, 0, 0);
cylinderX.rotation.x = degToRad(angleX);
cylinderX.rotation.y = degToRad(angleY);
cylinderX.rotation.z = degToRad(angleZ);
cylinderZ.rotation.x = degToRad(angleX);
cylinderZ.rotation.y = degToRad(angleY);
cylinderZ.rotation.z = degToRad(angleZ-90);
mesh.rotation.x = degToRad(angleX);
mesh.rotation.y = degToRad(angleY);
mesh.rotation.z = degToRad(angleZ);
render();
}
//renderowanie obiektów
function render() {
renderer.render( scene, camera );
}
I think the easiest way is to add the object to a parent Object3D, and move the object the appropriate distance (radius of the sphere you want to match the surface of) on one of the x, y or z axis. Add the parent to the scene and position it on the centre of the sphere you want to match (the child object should now fall on the sphere where that intersects the axis you used). With that set up like this, you can rotate the parent to position your object on the sphere.
Related
Im trying to roatate this space ship that i created, the rotation itself works the problem is that whenever i rotate it with the left and right arrow keys i want the spaceship to rotate just like with cartesian coordinates the problem is that whenever the objects rotates around the planet, the spaceship inclination doesnt change at all, like it would with cartesian coordinates and i dont get why really because the rotation around the planet itself works.
Sorry if the code is too long most of it is just to create the spaceship itself, i think the problem itself is in the update function itself.
Program:
/*global THREE*/
var camera = [];
var scene, renderer, currentCamera = 0;
var viewSize = 40;
var aspectRatio;
var geometry, material, mesh;
var wiredObjects = [];
var leftArrow, rightArrow, upArrow, downArrow;
var clock = new THREE.Clock();
//!!var controls;
var defaultScale = 1;
var planetRadius = 12;
var rocketHeight = planetRadius/12;
var rocketPartHeight = rocketHeight/2;
var rocketInfRadius = rocketPartHeight;
var rocketMidRadius = rocketPartHeight/2;
var rocketSupRadius = 0;
var boosterRadius = rocketInfRadius/5;
var boosterHeight = rocketInfRadius/4;
var rocketTrashDistance = 1.2 * planetRadius;
var objPositions = [];
var objAngles = [];
var nrTrash = 20;
var floatingTrash = [];
var trashSizes = [];
var minTrashSize = planetRadius/24;
var maxTrashSize = planetRadius/20;
var trashGeometries = [];
var copyVideo;
var universe;
var planet;
var rocket;
var loader = new THREE.TextureLoader();
var space_texture = new THREE.TextureLoader().load(
"https://wallpaperaccess.com/full/1268183.jpg"
);
'use strict';
function addObjPart(obj, geometry, mater, hex, x, y, z, rotX, rotY, rotZ) {
material = (mater != null)? mater : new THREE.MeshBasicMaterial({color: hex, wireframe: wires});
mesh = new THREE.Mesh(geometry, material);
mesh.rotateX(rotX);
mesh.rotateY(rotY);
mesh.rotateZ(rotZ);
mesh.position.set(x, y, z);
obj.add(mesh);
wiredObjects.push(mesh);
return mesh;
}
function getObjPositions() {
var i;
var nrObj = nrTrash+1;
var angleTheta, anglePhi;
var objX, objY, objZ;
var posVector = new THREE.Vector3(0,0,0); // spherical coordinates vector
var angleVector = new THREE.Vector2(0,0); // angles Theta and Phi for spherical coordinates
for (i = 0; i < nrObj; i++) {
angleTheta = Math.random() * 2*Math.PI;
anglePhi = Math.random() * 2*Math.PI;
angleVector.set(angleTheta, anglePhi);
objAngles.push(angleVector);
objX = rocketTrashDistance * Math.sin(angleTheta) * Math.sin(anglePhi);
objY = rocketTrashDistance * Math.cos(angleTheta);
objZ = rocketTrashDistance * Math.sin(angleTheta) * Math.cos(anglePhi);
posVector.set(objX, objY, objZ);
objPositions.push(posVector);
}
}
function createUniverse(x, y, z, scale) {
wires = true;
universe = new THREE.Object3D();
universe.scale.set(scale, scale, scale);
var rocketPos = objPositions[0];
addPlanet(universe, 0, 0, 0);
addRocket(universe, rocketPos.x, rocketPos.y, rocketPos.z);
addAux(universe);
universe.position.set(x, y, z);
scene.add(universe);
return universe;
}
function addPlanet(obj, x, y, z) {
planet = new THREE.Object3D();
geometry = new THREE.SphereGeometry(planetRadius);
var planetTexture = new THREE.TextureLoader().load(
"https://st2.depositphotos.com/5171687/44380/i/450/depositphotos_443805316-stock-photo-equirectangular-map-clouds-storms-earth.jpg"
);
var planetMaterial = new THREE.MeshBasicMaterial( {
map: planetTexture,
transparent:true,
side:THREE.DoubleSide,
} );
addObjPart(obj, geometry, planetMaterial, 0x0000ff, x, y, z, 0, 0, 0);
}
function addRocket(obj, x, y, z) {
rocket = new THREE.Group();
var n_rocket = new THREE.Object3D();
addRocketTop(n_rocket, 0, 0, -rocketPartHeight/2);
addRocketBottom(n_rocket, 0, 0, rocketPartHeight/2);
addRocketBooster(n_rocket, 0, rocketInfRadius-boosterRadius, rocketPartHeight+0.5*boosterHeight);
addRocketBooster(n_rocket, 0, -rocketInfRadius+boosterRadius,rocketPartHeight+0.5*boosterHeight);
addRocketBooster(n_rocket, rocketInfRadius-boosterRadius, 0, rocketPartHeight+0.5*boosterHeight);
addRocketBooster(n_rocket, -rocketInfRadius+boosterRadius, 0, rocketPartHeight+0.5*boosterHeight);
rocket.add(n_rocket);
rocket.position.set(x, y, z);
obj.add(rocket);
return rocket;
}
function addRocketTop(obj, x, y, z) {
geometry = new THREE.CylinderGeometry(rocketMidRadius, rocketSupRadius, rocketPartHeight, 41,1);
addObjPart(obj, geometry, null, 0xff0000, x, y, z, Math.PI/180*90, 0, 0);
}
function addRocketBottom(obj, x, y, z) {
geometry = new THREE.CylinderGeometry(rocketInfRadius, rocketMidRadius, rocketPartHeight, 41,1);
addObjPart(obj, geometry, null, 0x000fff, x, y, z, Math.PI/180*90, 0, 0);
}
function addRocketBooster(obj, x, y, z) {
geometry = new THREE.CapsuleGeometry(boosterRadius, boosterHeight, 0.5, 20);
addObjPart(obj, geometry, null, 0xff0000, x, y, z, Math.PI/180*90, 0, 0);
}
function addTrash(x, y, z) {
}
function render() {
renderer.render(scene, camera[currentCamera]); // tells 3js renderer to draw scene visualization based on camera
}
function onResize() {
if (window.innerWidth > 0 && window.innerHeight > 0){
var i;
var val = 2;
aspectRatio = window.innerWidth / window.innerHeight;
renderer.setSize(window.innerWidth, window.innerHeight);
var nrCameras = camera.length;
for (i = 0; i < 1; i++) { // Ortographic Cameras
camera[i].left = -viewSize * aspectRatio / val;
camera[i].right = viewSize * aspectRatio / val;
camera[i].top = viewSize / val;
camera[i].bottom = viewSize / -val;
camera[i].updateProjectionMatrix();
}
for (i=1; i < nrCameras; i++) { // Perspective cameras
camera[i].aspect = aspectRatio;
camera[i].updateProjectionMatrix();
}
}
}
function update()
{
var timeOccurred = clock.getDelta();
var rocketSpeed = Math.PI/180 * 40;
if (rightArrow || leftArrow || upArrow || downArrow) { // rocket movement flags
var rocketTheta = objAngles[0].x;
var rocketPhi = objAngles[0].y;
var rocketX, rocketY, rocketZ;
if (leftArrow){
rocketPhi += rocketSpeed * timeOccurred;
}
if (rightArrow){
//n_rocket.rotation.x += - rocketSpeed * timeOccurred;
rocketPhi += - rocketSpeed * timeOccurred;
}
if (upArrow){
//n_rocket.rotation.z += - rocketSpeed * timeOccurred;
rocketTheta += -rocketSpeed * timeOccurred;
}
if (downArrow){
//n_rocket.rotation.z += rocketSpeed * timeOccurred;
rocketTheta += rocketSpeed * timeOccurred;
}
rocketX = rocketTrashDistance * Math.sin(rocketTheta) * Math.sin(rocketPhi);
rocketY = rocketTrashDistance * Math.cos(rocketTheta);
rocketZ = rocketTrashDistance * Math.sin(rocketTheta) * Math.cos(rocketPhi);
rocket.position.set(rocketX, rocketY, rocketZ);
objAngles[0].set(rocketTheta, rocketPhi);
objPositions[0].set(rocketX, rocketY, rocketZ);
}
}
function animate() {
update();
requestAnimationFrame(animate);
// controls.update();
render();
}
function addAux(obj) {
geometry = new THREE.SphereGeometry(5);
addObjPart(obj, geometry, null, 0xffc0cb, 15, 0, 0);
addObjPart(obj, geometry, null, 0xffff00, 15, 0, 0);
addObjPart(obj, geometry, null, 0x0000ff, 15, 0, 0);
}
function createScene() {
scene = new THREE.Scene();
scene.add(new THREE.AxesHelper(100));
scene.background = space_texture;
getObjPositions();
universe = createUniverse(0, 0, 0, defaultScale);
}
function createOrtographicCamera(x, y, z) {
var val = 2;
aspectRatio = window.innerWidth / window.innerHeight;
var camera = new THREE.OrthographicCamera( viewSize * aspectRatio/-val,
viewSize * aspectRatio / val,
viewSize / val,
viewSize / -val,
1,
1000);
camera.position.x = x;
camera.position.y = y;
camera.position.z = z;
camera.lookAt(scene.position);
return camera;
}
function onKeyDown(e) {
var keyName = e.keyCode;
switch (keyName) {
case 49://1
currentCamera = 0;
break;
case 37 : // left arrow key
leftArrow = true;
break;
case 38: // up arrow key
upArrow = true;
break;
case 39: // right arrow key
rightArrow = true;
break;
case 40: // down arrow key
downArrow = true;
break;
default:
break;
}
}
function onKeyUp(e) {
var keyName = e.keyCode;
switch (keyName) {
case 37 : // left arrow key
leftArrow = false;
break;
case 38: // up arrow key
upArrow = false;
break;
case 39: // right arrow key
rightArrow = false;
break;
case 40: // down arrow key
downArrow = false;
break;
default:
break;
}
}
function init() {
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
createScene();
camera[0] = createOrtographicCamera(viewSize, 0, 0);
//!! controls = new THREE.OrbitControls(camera[0], renderer.domElement);
animate();
window.addEventListener("resize", onResize);
window.addEventListener("keydown", onKeyDown);
window.addEventListener("keyup", onKeyUp);
}
I want to join 2 Box Geometries to each other (image below) which are than drag rotatable as one object.
Below is the code for one drag-rotatable boxgeometry ( var geometry1 ), what do I need to add to the code, so that the second box geometry ( var geometry2 ) is joined to the first?
var three = THREE;
var space = new three.Scene();
var cam = new three.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var rend = new three.WebGLRenderer();
rend.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(rend.domElement);
var geometry1 = new three.BoxGeometry(1, 2, 1);
var geometry2 = new three.BoxGeometry(1, 1, 1);
var material = new three.MeshFaceMaterial([
new three.MeshBasicMaterial({
color: "red"
}),
new three.MeshBasicMaterial({
color: "orange"
}),
new three.MeshBasicMaterial({
color: "yellow"
}),
new three.MeshBasicMaterial({
color: "green"
}),
new three.MeshBasicMaterial({
color: "blue"
}),
new three.MeshBasicMaterial({
color: "cyan"
})
]);
var cube = new three.Mesh(geometry1, material);
cube.rotation.x = Math.PI / 4;
cube.rotation.y = Math.PI / 4;
space.add(cube);
cam.position.z = 5;
var Dragging = false;
var previousMousePosition = {
x: 0,
y: 0
};
$(rend.domElement).on('mousedown', function(e) {
Dragging = true;
})
.on('mousemove', function(e) {
//console.log(e);
var deltaMove = {
x: e.offsetX - previousMousePosition.x,
y: e.offsetY - previousMousePosition.y
};
if (Dragging) {
var deltaRotationQuaternion = new three.Quaternion()
.setFromEuler(new three.Euler(
toRadians(deltaMove.y * 1),
toRadians(deltaMove.x * 1),
0,
'XYZ'
));
cube.quaternion.multiplyQuaternions(deltaRotationQuaternion, cube.quaternion);
}
previousMousePosition = {
x: e.offsetX,
y: e.offsetY
};
});
$(document).on('mouseup', function(e) {
Dragging = false;
});
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var lastFrameTime = new Date().getTime() / 1000;
var totalGameTime = 0;
function update(dt, t) {
setTimeout(function() {
var TimeNow = new Date().getTime() / 1000;
var dt = TimeNow - (lastFrameTime || TimeNow);
totalGameTime += dt;
update(dt, totalGameTime);
lastFrameTime = TimeNow;
}, 0);
}
function render() {
rend.render(space, cam);
requestAnimFrame(render);
}
render();
update(0, totalGameTime);
function toRadians(angle) {
return angle * (Math.PI / 180);
}
function toDegrees(angle) {
return angle * (180 / Math.PI);
}
You can create a group:
var group = new THREE.Group();
group.add(geometry1);
group.add(geometry2);
scene.add(group);
Now you can change it's position, rotation, quaternion, normally, just by using the group variable.
I want to make a animated tube with hemisphere ends, the tubular segments is 200. I have the vertices from the first 60 segments to copy the position of a SphereGeometry's upper half part, and the last 60 segments lower half part.
The segments between the upper and lower hemisphere is all copied to the vertices around the sphere's equatorial.
The geometry looks fine, but the spherical environment mapping texture is discontinued at the sphere's equatorial.
I have my code as below, anyone know how to solve the problem?
var camera, scene, renderer;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 28, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 50;
scene = new THREE.Scene();
var nMat = new THREE.MeshNormalMaterial({side:THREE.DoubleSide,});
var tube = new DSTube( 200, 30, 10, nMat);
scene.add( tube.mesh );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
body {
margin: 0px;
background-color: #000000;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r78/three.js"></script>
<script>
function DSTube( lengthSeg, radiusSeg, radius, material ) {
//for speed
this.framerate = 60;
//center
this.origin = new THREE.Vector3();
this.head = this.origin;
this.tail = this.origin;
//setup
this.lengthSeg = lengthSeg;
this.radiusSeg = radiusSeg;
this.radius = radius;
this.pathPoints = [];
for(var i=0; i<this.lengthSeg; i++) {
this.pathPoints.push( new THREE.Vector3( 0, 0, 0) );
}
// TubeGeometry(path, tubularSegments, radius, radiusSegments, closed)
this.geometry = new THREE.TubeGeometry( new THREE.CatmullRomCurve3(this.pathPoints), this.lengthSeg, this.radius, this.radiusSeg, false );
this.material = material;
this.mesh = new THREE.Mesh( this.geometry, this.material );
this.verticeCount = this.geometry.vertices.length;
//sphere part
//adjust height segment if needed
this.sphereHeightSegments = 60;
//SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength)
this.headSphere = new THREE.SphereGeometry( this.radius, this.radiusSeg, this.sphereHeightSegments );
this.tailSphere = new THREE.SphereGeometry( this.radius, this.radiusSeg, this.sphereHeightSegments );
this.sphereVerticeCount = this.headSphere.vertices.length;
//count for tube hemisphere
this.headHemisphereVerticeCount = ( this.sphereHeightSegments / 2 + 1 ) * this.radiusSeg;
//layer
this.tubeLayerCount = this.lengthSeg + 1;
this.headHemisphereLayerCount = this.tailHemisphereLayerCount = this.sphereHeightSegments / 2 + 1;
this.tailHemisphereStartLayer = this.tubeLayerCount - this.sphereHeightSegments / 2;
this.middleLayerCount = this.tubeLayerCount - this.headHemisphereLayerCount * 2;
this.initGeometry();
// return this.mesh;
}
DSTube.prototype.initGeometry = function() {
this.copyHeadSphere();
this.copyInitialTubePart();
this.copyTailSphere();
}
DSTube.prototype.copyHeadSphere = function() {
//copy head hemisphere vertice
for( var y = 0; y < this.headHemisphereLayerCount; y++ ) {
for( var x = 0; x < this.radiusSeg; x++ ) {
if( x == 0 ) {
var sphereVertex = this.headSphere.vertices[ y * (this.radiusSeg + 1) + x ];
this.geometry.vertices[ y * this.radiusSeg + x ].copy( sphereVertex );
} else {
var sphereVertex = this.headSphere.vertices[ y * (this.radiusSeg + 1) + ( this.radiusSeg - x ) ];
this.geometry.vertices[ y * this.radiusSeg + x ].copy( sphereVertex );
}
}
}
this.geometry.computeBoundingSphere();
this.geometry.computeFaceNormals();
this.geometry.computeVertexNormals();
}
DSTube.prototype.copyInitialTubePart = function() {
//copy head hemisphere vertice
for( var y = this.headHemisphereLayerCount - 1; y < this.tubeLayerCount ; y++ ) {
for( var x = 0; x < this.radiusSeg; x++ ) {
var vertex = this.geometry.vertices[ ( this.headHemisphereLayerCount - 1 ) * this.radiusSeg + x ];
this.geometry.vertices[ y * this.radiusSeg + x ].copy( vertex );
}
}
this.geometry.computeBoundingSphere();
this.geometry.computeFaceNormals();
this.geometry.computeVertexNormals();
}
DSTube.prototype.copyTailSphere = function() {
//copy tail hemisphere vertice
for( var y = this.tailHemisphereStartLayer; y < this.tubeLayerCount; y++ ) {
for( var x = 0; x < this.radiusSeg; x++ ) {
if( x == 0 ) {
var sphereVertex = this.tailSphere.vertices[ ( y - this.middleLayerCount - 1 ) * (this.radiusSeg + 1) + x ];
this.geometry.vertices[ y * this.radiusSeg + x ].copy( sphereVertex );
} else {
var sphereVertex = this.tailSphere.vertices[ ( y - this.middleLayerCount - 1 ) * (this.radiusSeg + 1) + ( this.radiusSeg - x ) ];
this.geometry.vertices[ y * this.radiusSeg + x ].copy( sphereVertex );
}
}
}
this.geometry.computeBoundingSphere();
this.geometry.computeFaceNormals();
this.geometry.computeVertexNormals();
}
</script>
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();
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);