when I switch camera,camera control is bing valid - javascript

I want to swith camera type in my threejs Demo,so I read an official demo :https://threejs.org/examples/#webgl_camera
But some errors occur when I test my demo. When I press P to use cameraPerspective,it works well;But when I use O to switch cameraOrtho,cameracontrol doesn't work——I cannot rotate or move my model sample.
There is my code:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>3D-earth</title>
<script src="JSandCSS/jquery-2.2.4.min.js"></script>
<script src="JSandCSS/three.min.js"></script>
<script src="JSandCSS/OrbitControls.js"></script>
<script src="JSandCSS/OBJLoader.js"></script>
<script type="text/javascript" src="JSandCSS/jquery.qrcode.min.js"></script>
<script type="text/javascript" src="JSandCSS/qrcode.js"></script>
<script src="JSandCSS/bootstrap.min.js"></script>
<script type="text/javascript" src="JSandCSS/CanvasRenderer.js"></script>
<script src="JSandCSS/Projector.js"></script>
<link href="JSandCSS/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div style="width: 50%;">
<script>
var scene = new THREE.Scene();
var group = new THREE.Group;
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var objects = [];
init();
var container, stats, titleinfo;
scene.add(group);
var textureLoader = new THREE.TextureLoader();
var mat = new THREE.MeshLambertMaterial({
/* Roushness:1,
Metalness:0,*/
map: textureLoader.load("model/earth/texture.jpg"),
/* normalMap:textureLoader.load("model/earth/normal.jpg"),*/
specularMap: textureLoader.load("model/earth/specular.jpg"),
lightMap: textureLoader.load("model/earth/light.jpg"),
side:THREE.DoubleSide,
});
var loader = new THREE.OBJLoader();
loader.load('model/earth/earth.obj', function(obj) {
obj.traverse(function(child) {
if(child instanceof THREE.Mesh) {
child.material = mat;
}
});
mesh = obj;
obj.scale.set(2, 2, 2);
group.add(obj);
});
var light = new THREE.PointLight(0xffffff);
light.position.set(300, 400, 200);
light.intensity.set = 0.1;
scene.add(light);
scene.add(new THREE.AmbientLight(0x333333));
var cameraPerspective = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
cameraPerspective.position.set(200, 200, 200);
cameraPerspective.lookAt(scene.position);
cameraOrtho = new THREE.OrthographicCamera(window.innerWidth / -4, window.innerWidth / 4, window.innerHeight / 4, window.innerHeight / -4, -10000, 10000);
ActiveCamera = cameraPerspective;
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, ActiveCamera);
renderer.setClearColor(0x808080, 0.5);
var controls = new THREE.OrbitControls(ActiveCamera);
controls.minDistance = 200;
controls.maxDistance = 400;
controls.autoRotate = true;
controls.addEventListener('change', render);
animate();
window.addEventListener('resize', handleWindowResize, false);
document.addEventListener('keydown', onKeyDown, false);
function render() {
/*group.rotation.y -= 0.004;*/
renderer.render(scene, ActiveCamera);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function onKeyDown(event) {
switch(event.keyCode) {
case 79:
ActiveCamera = cameraOrtho;
case 80:
ActiveCamera = cameraPerspective;
}
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
renderer.setSize(WIDTH, HEIGHT);
ActiveCamera.aspect = WIDTH / HEIGHT;
ActiveCamera.updateProjectionMatrix();
}
</script>
</div>
</body>

try with single camera object of CombinedCamera and
to switch between Perspective and Ortho use below code.
//initial
var camera = new THREE.CombinedCamera($(canvasHold).innerWidth(), $(canvasHold).innerHeight(), 75, .1, 3e3, -5e3, 5e3);
camera.toOrthographic();
function switchCamera()
{
if(ortho) // Add condition
{
camera.toOrthographic();
camera.position.set(0, 0, 0);
camera.zoom = .5;
camera.up = new THREE.Vector3(0, 0, 0);
camera.lookAt(scene.position);
camera.setFov(75);
}
else
{
camera.toPerspective();
camera.zoom = 1;
camera.setFov(45);
}
}
Note: Please change variables and values according to your requirements.

Related

How would you place hyperlinks on 3D Objects/Mesh using ThREE?

I am trying to create a simple box that can link when clicked.
It sounds simple but it didn't work for me so help is appreciated. I've been trying to find answers to this, I don't know what I did wrong. I found like only 2 questions about this on stackoverflow but they still didn't help me answer.
const coolTexture = new THREE.TextureLoader().load('cool.jpg');
const cool = new THREE.Mesh(
new THREE.BoxGeometry(3, 3, 3),
new THREE.MeshBasicMaterial({
color: Math.random() * 0xffffff
})
);
cool.userData = {
URL: "http://stackoverflow.com"
};
scene.add(cool);
function linki() {
if (intersects.length > 0) {
window.open(intersects[0].object.userData.URL);
}
}
document.body.onclick = linki
If it's going to be only one box then use window.open(object.URL); when pointerdown event is detected.
let scene, camera, renderer, cube;
window.addEventListener("pointerdown", () => {
window.open(cube.URL);
});
//
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xf79862);
camera = new THREE.PerspectiveCamera(
90,
window.innerWidth / window.innerHeight,
1,
1000
);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const color = 0xffffff;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
const geometry = new THREE.BoxGeometry(3, 3, 0.05);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
cube = new THREE.Mesh(geometry, material);
cube.position.set(0, 0, -2);
cube.URL = "http://stackoverflow.com";
scene.add(cube);
renderer.setAnimationLoop(loop);
}
function loop() {
renderer.render(scene, camera);
}
init();
body {
font-family: sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.145.0/three.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<script src="src/index.js">
</script>
</body>
</html>
But if you plan to create more URLs you should use Raycaster and check which box was clicked.
let scene, camera, renderer;
let objsToTest = [];
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
mouse.x = mouse.y = null;
window.addEventListener("pointermove", (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
});
let selectState = false;
window.addEventListener("pointerdown", () => {
selectState = true;
});
window.addEventListener("pointerup", () => {
selectState = false;
});
window.addEventListener("touchstart", (event) => {
selectState = true;
mouse.x = (event.touches[0].clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.touches[0].clientY / window.innerHeight) * 2 + 1;
});
window.addEventListener("touchend", () => {
selectState = false;
mouse.x = null;
mouse.y = null;
});
//
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xf79862);
camera = new THREE.PerspectiveCamera(
90,
window.innerWidth / window.innerHeight,
1,
1000
);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const color = 0xffffff;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
const geometry = new THREE.BoxGeometry(0.5, 0.3, 0.05);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
cube.position.set(-0.5, 0, -2);
cube.URL = "url1";
scene.add(cube);
const material2 = new THREE.MeshBasicMaterial({ color: 0xffff00 });
const cube2 = new THREE.Mesh(geometry, material2);
cube2.position.set(0.5, 0, -2);
cube2.URL = "url2";
scene.add(cube2);
objsToTest.push(cube, cube2);
renderer.setAnimationLoop(loop);
}
function loop() {
renderer.render(scene, camera);
updateButtons();
}
function updateButtons() {
let intersect;
if (mouse.x !== null && mouse.y !== null) {
raycaster.setFromCamera(mouse, camera);
intersect = raycast();
}
if (intersect && selectState) {
window.open(intersect.object.URL);
}
}
//
function raycast() {
return objsToTest.reduce((closestIntersection, obj) => {
const intersection = raycaster.intersectObject(obj, true);
if (!intersection[0]) return closestIntersection;
if (
!closestIntersection ||
intersection[0].distance < closestIntersection.distance
) {
intersection[0].object = obj;
return intersection[0];
}
return closestIntersection;
}, null);
}
init();
body {
font-family: sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.145.0/three.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<script src="src/index.js">
</script>
</body>
</html>

What did i do wrong here? The 3D module is not showing up

I am trying to use three.js to open an obj 3d module, but for some reason i cannot manage to generate the module out on the web, is there anything wrong i done here? (i just directly follow this tutorial video https://www.youtube.com/watch?v=wHuSQ7I1aKs)
My obj and mtl file is at directory "/Documents/js/bugatti" while my html file is at "/Documents/js"
<!DOCTYPE html>
<html>
<head>
<title>My first three.js app</title>
<style>
body { margin: 0; }
canvas {width: 100%; height: 100%}
</style>
</head>
<body>
<script src="OrbitControls.js"></script>
<script src="three.min.js"></script>
<script type = "module" src="OBJLoader.js"></script>
<script type = "module" src="MTLLoader.js"></script>
<script type = "module">
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 200;
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = true;
var keyLight = new THREE.DirectionalLight(new THREE.Color('hsl(30, 100%, 75%)'), 1.0);
keyLight.position.set(-100, 0, 100);
var fillLight = new THREE.DirectionalLight(new THREE.Color('hsl(240, 100%, 75%)'), 0.75);
fillLight.position.set(100, 0, 100);
var backLight = new THREE.DirectionalLight(0xffffff, 1.0);
backLight.position.set(100, 0, -100).normalize();
scene.add(keyLight);
scene.add(fillLight);
scene.add(backLight);
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setTexturePath('/Document/js/bugatti/');
mtlLoader.setPath('/Documents/js/bugatti/');
mtlLoader.load('bugatti.mtl', function (materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('/Documents/js/bugatti/');
objLoader.load('bugatti.obj', function (object) {
scene.add(object);
object.position.y -= 60;
});
});
var animate = function () {
requestAnimationFrame( animate );
controls.update();
renderer.render(scene, camera);
};
animate();
</script>
</body>
</html>

Three.js - Animation is not playing

I have problem with animating object exported via blender plugin from blender to THREE.js. Animation did not start running...
Of course, I tried many combinations of settings when exporting from blender and importing to THREE.js library, but without success.
Here is code, what I think should work. Comment Critical section annotate where is probably some mistake. Link to source JSON is in the example too. Of course, I can provide source *.blend file, if needed...
var tgaLoader = new THREE.TGALoader();
var objectLoader = new THREE.ObjectLoader();
var clock = new THREE.Clock();
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
document.getElementById('container').appendChild(renderer.domElement);
objectLoader.load('//cdn.rawgit.com/PiranhaGreg/files/master/scavenger.json', function (loadedScene) {
scene = loadedScene;
mesh = scene.children[0];
scene.background = new THREE.Color('white');
mesh.material = new THREE.MeshPhongMaterial({ map: tgaLoader.load('//cdn.rawgit.com/PiranhaGreg/files/master/SCA_BODY_V0.TGA') });
hemiLight = new THREE.HemisphereLight('white', 'white', 0.6);
scene.add(hemiLight);
camera = new THREE.PerspectiveCamera(30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000);
camera.position.set(500, 200, -100);
controls = new THREE.OrbitControls(camera);
controls.target.set(0, 50, 0);
controls.update();
var geometry = new THREE.PlaneBufferGeometry(200, 200);
var material = new THREE.MeshPhongMaterial({ shininess: 0.1 });
var ground = new THREE.Mesh(geometry, material);
ground.rotation.x = - Math.PI / 2;
scene.add(ground);
mesh.scale.set(-1, -1, 1);
// Critical section...
mixer = new THREE.AnimationMixer(mesh);
var sequence = THREE.AnimationClip.CreateFromMorphTargetSequence('animation', mesh.geometry.morphTargets, 25, true);
var animation = mixer.clipAction(sequence);
animation.play();
// End of critital section
animate();
});
window.onresize = function() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
};
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
var delta = 0.75 * clock.getDelta();
mixer.update(delta);
renderer.render(scene, camera);
}
body {
margin: 0px;
overflow: hidden;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js"></script>
<script src="//cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/TGALoader.js" type="application/javascript"></script>
<script src="//cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>
<div id="container"></div>
Thanks for any suggestion.
I dug in into animation and noticed that it uses morphTargets. And then I remembered about this example. So, the key moment is to set .morphTarget parameter of a material to true, so, I've applied it to the material in your code snippet and it started to work:
mesh.material = new THREE.MeshPhongMaterial({
map: tgaLoader.load('//cdn.rawgit.com/PiranhaGreg/files/master/SCA_BODY_V0.TGA'),
morphTargets: true
});
Though, I'm not sure, if such an approach is correct, but, at least, it's working )
var tgaLoader = new THREE.TGALoader();
var objectLoader = new THREE.ObjectLoader();
var clock = new THREE.Clock();
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
document.getElementById('container').appendChild(renderer.domElement);
objectLoader.load('//cdn.rawgit.com/PiranhaGreg/files/master/scavenger.json', function (loadedScene) {
scene = loadedScene;
mesh = scene.children[0];
scene.background = new THREE.Color('white');
mesh.material = new THREE.MeshPhongMaterial({ map: tgaLoader.load('//cdn.rawgit.com/PiranhaGreg/files/master/SCA_BODY_V0.TGA'), morphTargets: true });
hemiLight = new THREE.HemisphereLight('white', 'white', 0.6);
scene.add(hemiLight);
camera = new THREE.PerspectiveCamera(30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000);
camera.position.set(500, 200, -100);
controls = new THREE.OrbitControls(camera);
controls.target.set(0, 50, 0);
controls.update();
var geometry = new THREE.PlaneBufferGeometry(200, 200);
var material = new THREE.MeshPhongMaterial({ shininess: 0.1 });
var ground = new THREE.Mesh(geometry, material);
ground.rotation.x = - Math.PI / 2;
scene.add(ground);
mesh.scale.set(-1, -1, 1);
// Critical section...
mixer = new THREE.AnimationMixer(mesh);
var sequence = THREE.AnimationClip.CreateFromMorphTargetSequence('animation', mesh.geometry.morphTargets, 25, true);
var animation = mixer.clipAction(sequence);
animation.play();
// End of critital section
animate();
});
window.onresize = function() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
};
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
var delta = 0.75 * clock.getDelta();
mixer.update(delta);
renderer.render(scene, camera);
}
body {
margin: 0px;
overflow: hidden;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js"></script>
<script src="//cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/TGALoader.js" type="application/javascript"></script>
<script src="//cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>
<div id="container"></div>

three.js adding object to scene but not rendering object

I'm creating a function createCylinder(n, len, rad) that is called from function createScene(). I have checked that the vertices and faces are added and I get no errors. However, the geometry is not rendered. I suppose this has to do with the timing of returning the geometry or returning the mesh and adding it to the scene. That being said, I have tried everything I could think of and found no solution. Can someone please help me figure this out? Thanks in advance!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cylinder</title>
</head>
<script type="text/javascript" src="three.js"></script>
<script type="text/javascript" src="OrbitControls.js"></script>
<style>
body {
/* set margin to 0 and overflow to hidden, to go fullscreen */
margin: 0;
overflow: hidden;
}
</style>
<body>
<div id="container">
</div>
<div id="msg">
</div>
<script type="text/javascript">
var camera, scene, renderer;
var cameraControls;
var clock = new THREE.Clock();
var isCappedBottom = false;
var isCappedTop = false;
function createCylinder(n, len, rad) {
var geometry = new THREE.Geometry();
var radius = rad;
var length = len;
var yUp = length / 2;
var yDown = -length / 2;
var theta = (2.0 * Math.PI) / n;
for (var i = 0; i < n ; i++) { //runs n + 2 times if we allow redundant vertices
var x = radius * Math.cos(i * theta);
var z = radius * Math.sin(i * theta);
//Top to bottom
var originUp = new THREE.Vector3(x, yUp, z);
var originDown = new THREE.Vector3(x, yDown, z);
geometry.vertices.push(originUp); //0
geometry.vertices.push(originDown); //1
console.log("Vertices " + geometry.vertices.length);
}//end of first for loop
// Draw faces
for (var j = 0; j < 2*n; j+= 2) {
var face1 = new THREE.Face3(j, j + 1, j + 2);
var face2 = new THREE.Face3(j + 1, j + 3, j + 2);
geometry.faces.push(face1);
geometry.faces.push(face2);
console.log("faces " + geometry.faces.length);
}
// return geometry;
//scene.add(geometry);
var material = new THREE.MeshLambertMaterial({color: 0xFF0000, side: THREE.DoubleSide});
var mesh = new THREE.Mesh(geometry, material);
return mesh;
scene.add(mesh);
// add subtle ambient lighting
var ambientLight = new THREE.AmbientLight(0x222222);
scene.add(ambientLight);
var light = new THREE.PointLight(0xFFFFFF, 1, 1000);
light.position.set(0, 10, 20);
scene.add(light);
var light2 = new THREE.PointLight(0xFFFFFF, 1, 1000);
light2.position.set(0, -10, -10);
scene.add(light2);
} //End of function
function createScene() {
var cyl = createCylinder(10, 10, 2);
return cyl;
scene.add(cyl);
}
function animate() {
window.requestAnimationFrame(animate);
render();
}
function render() {
var delta = clock.getDelta();
cameraControls.update(delta);
renderer.render(scene, camera);
}
function init() {
var canvasWidth = window.innerWidth;
var canvasHeight = window.innerHeight;
var canvasRatio = canvasWidth / canvasHeight;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({antialias: true, preserveDrawingBuffer: true});
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.setSize(canvasWidth, canvasHeight);
renderer.setClearColor(0x000000, 1.0);
renderer.shadowMapEnabled = true;
camera = new THREE.PerspectiveCamera( 40, canvasRatio, 1, 1000);
/* camera.position.z = 5;
camera.lookAt(scene.position); */
camera.position.set(0, 0, 12);
camera.lookAt(new THREE.Vector3(0, 0, 0));
cameraControls = new THREE.OrbitControls(camera, renderer.domElement);
}
function addToDOM() {
var container = document.getElementById('container');
var canvas = container.getElementsByTagName('canvas');
if (canvas.length>0) {
container.removeChild(canvas[0]);
}
container.appendChild( renderer.domElement );
}
init();
createScene();
addToDOM();
render();
animate();
</script>
</body>
</html>
In the createCylinder function:
var mesh = new THREE.Mesh(geometry, material);
return mesh; // this line must be the last line in the function
// after return(), the rest of the code is unreacheable
//scene.add(mesh); // this line should be deleted as you add the mesh in the createScene() function
and then the createScene function should be like this:
function createScene() {
var cyl = createCylinder(10, 10, 2);
//return cyl;
scene.add(cyl);
}
jsfiddle example

Why raycaster.intersectObjects work fine with Geometry built in scene but work bad with model loaded form exterior?

I wanna make a measure tool in three.js,and I use reycaster function to do it.
When I use it with Geometry built in scene,it was fine.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ytest</title>
<script src="JSandCSS/three.js"></script>
<script src="JSandCSS/OrbitControls.js"></script>
<script src="JSandCSS/OBJLoader.js"></script>
<script src="JSandCSS/Raycaster.js"></script>
</head>
<body>
<script>
var scene = new THREE.Scene();
var group = new THREE.Group;
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var objects = [];
var particleMaterial;
particlecount = 0;
var container, stats, titleinfo;
scene.add(group);
var geometry = new THREE.SphereGeometry(5, 32, 32);
geometry.scale(10, 10, 10);
var material = new THREE.MeshBasicMaterial({
color: 0xffff00
});
var sphere = new THREE.Mesh(geometry, material);
group.add(sphere);
objects.push(sphere);
var light = new THREE.PointLight(0xffffff);
light.position.set(300, 400, 200);
light.intensity.set = 0.1;
scene.add(light);
scene.add(new THREE.AmbientLight(0x333333));
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(200, 200, 200);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
renderer.setClearColor(0x808080, 0.5);
render();
var controls = new THREE.OrbitControls(camera);
controls.addEventListener('change', render);
animate();
window.addEventListener('resize', handleWindowResize, false);
window.addEventListener('mousedown', onDocumentMouseDown, false);
function onDocumentMouseDown(event) {
event.preventDefault();
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects);
var PI2 = Math.PI * 2;
var pointLoader = new THREE.TextureLoader();
particleMaterial = new THREE.SpriteMaterial({
map: pointLoader.load("pic/measurepoint.png"),
});
if(intersects.length > 0) {
if(particlecount == 0) {
var particle1 = new THREE.Sprite(particleMaterial);
particle1.name = 'particle1';
particle1.position.copy(intersects[0].point);
particle1.scale.x = particle1.scale.y = 5;
scene.add(particle1);
particlecount = 1;
} else {
if(particlecount !== 2) {
var particle2 = new THREE.Sprite(particleMaterial);
particle2.name = 'particle2';
particle2.position.copy(intersects[0].point);
particle2.scale.x = particle2.scale.y = 5;
scene.add(particle2);
particlecount = 2;
a = scene.getObjectByName('particle1');
b = scene.getObjectByName('particle2');
var dis = a.position.distanceTo(b.position);
alert('distance between two point is' + dis);
scene.remove(a);
scene.remove(b);
particlecount = 0;
}
}
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
}
</script>
</body>
</html>
enter image description here
But When I loaded a model,it doesn't work.As you see result of "alert(intersects.length)" is 0.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ytest</title>
<script src="JSandCSS/three.js"></script>
<script src="JSandCSS/OrbitControls.js"></script>
<script src="JSandCSS/OBJLoader.js"></script>
<script src="JSandCSS/Raycaster.js"></script>
</head>
<body>
<script>
var scene = new THREE.Scene();
var group = new THREE.Group;
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var objects = [];
var particleMaterial;
particlecount = 0;
var container, stats, titleinfo;
scene.add(group);
var textureLoader = new THREE.TextureLoader();
var mat = new THREE.MeshLambertMaterial({
map: textureLoader.load("model/earth/texture.jpg"),
specularMap: textureLoader.load("model/earth/specular.jpg"),
lightMap: textureLoader.load("model/earth/light.jpg")
});
var loader = new THREE.OBJLoader();
loader.load('model/earth/earth.obj',
function chuanzhi(obj) {
obj.traverse(function(child) {
if(child instanceof THREE.Mesh) {
child.material = mat;
}
});
Mesh = obj;
obj.scale.set(2, 2, 2);
group.add(obj);
objects.push(Mesh);
});
var light = new THREE.PointLight(0xffffff);
light.position.set(300, 400, 200);
light.intensity.set = 0.1;
scene.add(light);
scene.add(new THREE.AmbientLight(0x333333));
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(200, 200, 200);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
renderer.setClearColor(0x808080, 0.5);
render();
var controls = new THREE.OrbitControls(camera);
controls.addEventListener('change', render);
animate();
window.addEventListener('resize', handleWindowResize, false);
window.addEventListener('mousedown', onDocumentMouseDown, false);
function onDocumentMouseDown(event) {
event.preventDefault();
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects);
var PI2 = Math.PI * 2;
var pointLoader = new THREE.TextureLoader();
particleMaterial = new THREE.SpriteMaterial({
map: pointLoader.load("pic/measurepoint.png"),
});
alert(intersects.length);
if(intersects.length > 0) {
if(particlecount == 0) {
var particle1 = new THREE.Sprite(particleMaterial);
particle1.name = 'particle1';
particle1.position.copy(intersects[0].point);
particle1.scale.x = particle1.scale.y = 5;
scene.add(particle1);
particlecount = 1;
} else {
if(particlecount !== 2) {
var particle2 = new THREE.Sprite(particleMaterial);
particle2.name = 'particle2';
particle2.position.copy(intersects[0].point);
particle2.scale.x = particle2.scale.y = 5;
scene.add(particle2);
particlecount = 2;
a = scene.getObjectByName('particle1');
b = scene.getObjectByName('particle2');
var dis = a.position.distanceTo(b.position);
alert('distance between two point is' + dis);
scene.remove(a);
scene.remove(b);
particlecount = 0;
}
}
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
}
</script>
</body>
</html>
I wanna know why it happened,and how I can use it correctly.Could you help me ?

Categories

Resources