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);
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);
}
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();
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 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.
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);
}