I am running into a bit of difficulty selecting objects with the orthographic camera using the raycaster. Though, I have no problem with it when I use a perspective camera. The only thing I am changing when switching between the two is the type camera.
I am able to select faces on the orthographic view, but it is only loosely related to where I am clicking on the screen. When I can click far away from the object and it will still come back as if it has hit the object near its center.
Any ideas on what I am missing here?
I am basing much of my code on this example, and am hoping to achieve a very similar result from my code. (this example I'm referencing uses the perspective camera)
Any help is much appreciated
<html>
<head>
<style>
canvas {
left: 0;
top: 0;
width: 100%;
height: 100%;
position: fixed;
background-color: #111115;
}
</style>
</head>
<body id='c'>
<script src="js/three.js"></script>
<script>
var obj = [];
var mouse ={};
var zoom = 2;
var scene = new THREE.Scene();
//switch between these two and see the difference:
//var camera = new THREE.OrthographicCamera(window.innerWidth / -zoom, window.innerWidth / zoom, window.innerHeight / zoom, window.innerHeight / -zoom, -1000, 1000);
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position = new THREE.Vector3(100,100,100);
camera.lookAt(new THREE.Vector3(0,0,0));
// this material causes a mesh to use colors assigned to faces
var material = new THREE.MeshBasicMaterial(
{ color: 0xffffff, vertexColors: THREE.FaceColors } );
var sphereGeometry = new THREE.SphereGeometry( 80, 32, 16 );
for ( var i = 0; i < sphereGeometry.faces.length; i++ )
{
face = sphereGeometry.faces[ i ];
face.color.setRGB( 0, 0, 0.8 * Math.random() + 0.2 );
}
obj['box'] = {};
obj['box'] = new THREE.Mesh( sphereGeometry, material );
obj['box'].castShadow = true;
obj['box'].receiveShadow = true;
scene.add(obj['box']);
var ambientLight = new THREE.AmbientLight(0xbbbbbb);
scene.add(ambientLight);
var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(-100, 40, 100);
directionalLight.castShadow = true;
directionalLight.shadowOnly = true;
directionalLight.shadowDarkness = .5;
scene.add(directionalLight);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
document.body.appendChild(renderer.domElement);
projector = new THREE.Projector();
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
function onDocumentMouseDown( event ) {
// the following line would stop any other event handler from firing
// (such as the mouse's TrackballControls)
// event.preventDefault();
console.log("Click.");
// update the mouse variable
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
// find intersections
// create a Ray with origin at the mouse position
// and direction into the scene (camera direction)
var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
projector.unprojectVector( vector, camera );
var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
// create an array containing all objects in the scene with which the ray intersects
var intersects = ray.intersectObjects( [obj['box']] );
// if there is one (or more) intersections
if ( intersects.length > 0 )
{
console.log("Hit # " + toString( intersects[0].point ) );
console.log(intersects);
// change the color of the closest face.
intersects[ 0 ].face.color.setRGB( 0.8 * Math.random() + 0.2, 0, 0 );
intersects[ 0 ].object.geometry.colorsNeedUpdate = true;
}
}
function toString(v) { return "[ " + v.x + ", " + v.y + ", " + v.z + " ]"; }
var render = function() {
requestAnimationFrame(render);
renderer.render(scene, camera);
};
console.log(camera);
console.log(obj['box'])
render();
</script>
</body>
I am hoping it is something simple that I just don't know about yet.
three.js r60
Here is the pattern to use when raycasting with either an orthographic camera or perspective camera:
var raycaster = new THREE.Raycaster(); // create once
var mouse = new THREE.Vector2(); // create once
...
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, recursiveFlag );
three.js r.84
One more note that might save you some trouble. If you have a camera like this:
var camera = new THREE.OrthographicCamera(0, window.innerWidth, -window.innerHeight, 0, -100, 100);
Then during raycasting, be sure to move the ray origin.z to camera.far for it to hit anything in the entire visible range:
this.ray.origin.set(0, 0, 0);
this.camera.localToWorld(this.ray.origin);
this.ray.setFromCamera(this.mouseCoord, this.camera);
this.ray.origin.z = this.camera.far;
Related
I have this really simple test scene to place a bunch of html labels on the position of a 3d object in my scene. But when ever i try converting the 3d coordinates to the screen location i get weird values that do not at all corrosponded with the position of my 3d object. See below for the code with which i generate a scene and place a label:
var CanvasContainer = document.getElementById("KettingContainer");
function CameraSetup(container){
var camera = new THREE.PerspectiveCamera( 50, container.offsetWidth / container.offsetHeight, 1, 300 );
camera.position.set( 0, 0, 100 );
camera.lookAt( 0, 0, 0 );
return camera;
}
function SceneSetup(){
var scene = new THREE.Scene();
return scene;
}
function RenderSetup(container) {
var renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.autoClear = false;
renderer.setClearColor( 0x000000, 0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( container.offsetWidth, container.offsetHeight );
container.appendChild( renderer.domElement );
return renderer;
}
function OnWindowResize(container){
camera.aspect = container.offsetWidth / container.offsetHeight;
camera.updateProjectionMatrix();
renderer.setSize( container.offsetWidth, container.offsetHeight );
}
var kraalLabels = document.getElementById('kraalLinkLabels').getElementsByTagName('div');
function Animate(){
requestAnimationFrame(Animate);
Render();
}
function Render(){
renderer.render( scene, camera );
}
function createScreenVector(pos, camera, width, height) {
const hw = width/2, hh = height/2;
var pos2d = pos.clone();
pos2d.project(camera);
console.log(pos2d);
pos2d.x = ( pos2d.x * hw ) + hw;
pos2d.y = - ( pos2d.y * hh ) + hh;
return pos2d;
}
function positionLabels(positions, camera, width, height){
for( var i = 0; i < kraalLabels.length; i++ )
{
const d = createScreenVector(positions, camera, width, height);
kraalLabels[i].style.left = d.x + "px";
kraalLabels[i].style.top = d.y + "px";
}
}
var camera = CameraSetup(CanvasContainer);
var scene = SceneSetup();
var renderer = RenderSetup(CanvasContainer);
console.log("fc: ", camera.position);
const geometry = new THREE.SphereGeometry( 10, 32, 32 );
const material = new THREE.MeshBasicMaterial( {color: 0xff0000} );
let sphere = new THREE.Mesh( geometry, material );
sphere.position.set(20, 20, 0.1);
scene.add( sphere );
positionLabels(new THREE.Vector3(20, 20, 0.1), camera, CanvasContainer.offsetWidth, CanvasContainer.offsetHeight);
window.addEventListener("resize", function(){ OnWindowResize(CanvasContainer); }, false);
Animate();
See below a screenshot of the camera position, the canvas container size, and the screen location for each of the labels:
As you can see the positions of the labels are huge way bigger then the canvas itself. And the positions are all in the negative...
Even doh my object is just a bit to the top and left of the center of the screen..
I am completely stuck at this time i have no clue what i am doing wrong :(
If extra information is needed i am happy to clarify!
After searching for a solution for houres upon hours i finally found the problem before you do the vector3.project(camera); you have to update the camera matrix like so: camera.updateMatrixWorld(); this will fix the problem with weird values.
Hopes this helps someone in the future!
I am using this example for my WebGL panorama cube: https://threejs.org/examples/?q=pano#webgl_panorama_equirectangular
I want to know what cube user clicks on and I discovered I can use Raycaster for this. According to docs I added the following function:
function onMouseDown( event ) {
event.preventDefault();
var mouseVector = new THREE.Vector3(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
1 );
//projector.unprojectVector( mouseVector, camera );
mouseVector.unproject( camera );
var raycaster = new THREE.Raycaster( camera.position, mouseVector.sub( camera.position ).normalize() );
// create an array containing all objects in the scene with which the ray intersects
var intersects = raycaster.intersectObjects( scene.children );
console.log(intersects);
if (intersects.length>0){
console.log("Intersected object:", intersects.length);
intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
}
// ...
But intersects is always empty. My scene is defined as
scene = new THREE.Scene();
and has skyBox added:
var skyBox = new THREE.Mesh( new THREE.CubeGeometry( 1, 1, 1 ), materials );
skyBox.applyMatrix( new THREE.Matrix4().makeScale( 1, 1, - 1 ) );
scene.add( skyBox );
I've seen similar posts related to this issue but could not figure out how to apply to this example. Any directions are appreciated.
Try adding this to your material definition:
var materials = new THREE.SomeMaterial({
/* other settings */,
side: THREE.DoubleSide
});
Raycaster won't intersect back-faces unless the side property is set to THREE.BackSide or THREE.DoubleSide. Even though your scaling technically inverts the face direction, the vertex order stays the same, which is what's important to Raycaster.
Some further explanation
The snippet below is showing how a ray projected from a camera at the center of a skybox inverted by a -Z scale might look.
The box itself looks weird because it has been -Z scaled, and the normals no longer match the material. But that's here nor there.
The green arrow represents the original ray. The red arrow represents what will happen to that ray inside the Mesh.raycast function, which will apply the inverse of the object's world matrix to the ray, but not to the object's geometry. This is a whole different problem.
The point I'm making is that within Mesh.raycast, it does not affect the vertex/index order, so when it checks the triangles of the mesh, they are still in their original order. For a standard BoxGeometry/BoxBufferGeometry, this means the faces all face outward from the geometric origin.
This means the rays (regardless of how the transformation matrix affects them) are still trying to intersect the back-face of those triangles, which will not work unless the material is set to THREE.DoubleSide. (It can also be set to THREE.BackSide, but the -Z scale will ruin that.)
Clicking either of the raycast buttons will produce 0 intersects if the -Z scaled box is not set to THREE.DoubleSide (default). Click the "Set THREE.DoubleSide" button and try it again--it will now intersect.
var renderer, scene, camera, controls, stats;
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight,
FOV = 35,
NEAR = 1,
FAR = 1000,
ray1, ray2, mesh;
function populateScene(){
var cubeGeo = new THREE.BoxBufferGeometry(10, 10, 10),
cubeMat = new THREE.MeshPhongMaterial({ color: "red", transparent: true, opacity: 0.5 });
mesh = new THREE.Mesh(cubeGeo, cubeMat);
mesh.applyMatrix( new THREE.Matrix4().makeScale( 1, 1, -1 ) );
mesh.updateMatrixWorld(true);
scene.add(mesh);
var dir = new THREE.Vector3(0.5, 0.5, 1);
dir.normalize();
ray1 = new THREE.Ray(new THREE.Vector3(), dir);
var arrow1 = new THREE.ArrowHelper(ray1.direction, ray1.origin, 20, 0x00ff00);
scene.add(arrow1);
var inverseMatrix = new THREE.Matrix4();
inverseMatrix.getInverse(mesh.matrixWorld);
ray2 = ray1.clone();
ray2.applyMatrix4(inverseMatrix);
var arrow2 = new THREE.ArrowHelper(ray2.direction, ray2.origin, 20, 0xff0000);
scene.add(arrow2);
}
function init() {
document.body.style.backgroundColor = "slateGray";
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
document.body.appendChild(renderer.domElement);
document.body.style.overflow = "hidden";
document.body.style.margin = "0";
document.body.style.padding = "0";
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(FOV, WIDTH / HEIGHT, NEAR, FAR);
camera.position.z = 50;
scene.add(camera);
controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.dynamicDampingFactor = 0.5;
controls.rotateSpeed = 3;
var light = new THREE.PointLight(0xffffff, 1, Infinity);
camera.add(light);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0';
document.body.appendChild(stats.domElement);
resize();
window.onresize = resize;
populateScene();
animate();
var rayCaster = new THREE.Raycaster();
document.getElementById("greenCast").addEventListener("click", function(){
rayCaster.ray.copy(ray1);
alert(rayCaster.intersectObject(mesh).length + " intersections!");
});
document.getElementById("redCast").addEventListener("click", function(){
rayCaster.ray.copy(ray2);
alert(rayCaster.intersectObject(mesh).length + " intersections!");
});
document.getElementById("setSide").addEventListener("click", function(){
mesh.material.side = THREE.DoubleSide;
mesh.material.needsUpdate = true;
});
}
function resize() {
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
if (renderer && camera && controls) {
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
controls.handleResize();
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
controls.update();
stats.update();
}
function threeReady() {
init();
}
(function () {
function addScript(url, callback) {
callback = callback || function () { };
var script = document.createElement("script");
script.addEventListener("load", callback);
script.setAttribute("src", url);
document.head.appendChild(script);
}
addScript("https://threejs.org/build/three.js", function () {
addScript("https://threejs.org/examples/js/controls/TrackballControls.js", function () {
addScript("https://threejs.org/examples/js/libs/stats.min.js", function () {
threeReady();
})
})
})
})();
body{
text-align: center;
}
<input id="greenCast" type="button" value="Cast Green">
<input id="redCast" type="button" value="Cast Red">
<input id="setSide" type="button" value="Set THREE.DoubleSide">
You might actually want to use an easier process to determine your ray from the camera:
THREE.Raycaster.prototype.setFromCamera( Vector2, Camera );
Simply define your mouse coordinates as you do in a Vector2, then pass the elements to the Raycaster and let it do its thing. It hides the complexity of intersecting the frustrum with the ray from the camera, and should solve your problem.
(Also, the raycaster does indeed only intersect faces that face the ray directly, but since your SkyBox has been inverted its geometries faces are pointing to the inside of the box, so they should intersect if the camera is inside the box. Another possibility is that your box is further away than the raycasters default far value.)
function onMouseDown( event ) {
event.preventDefault();
var mouseVector = new THREE.Vector2(
event.clientX / window.innerWidth * 2 - 1,
-event.clientY / window.innerHeight * 2 + 1
);
var raycaster = new THREE.Raycaster;
raycaster.setFromCamera( mouseVector, camera );
var intersects = raycaster.intersectObjects( scene.children );
console.log(intersects);
if( intersects.length > 0 ){
console.log( "Intersected object:", intersects[ 0 ] );
intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
}
}
I have the following JavaScript code, taken from an example, which draws some circles, and when you click on one of them, it changes color. But I also want to change the radius/size of a circle when you click on that circle (and leave the other circles unchanged). The documentation does not help at all, and I have tried several variations in the code like
intersects[ 0 ].object.geometry.parameters.radius = 50;
intersects[ 0 ].object.geometry.radius = 50;
intersects[ 0 ].object.geometry.setRadius(50);
Anyway, here is the complete code:
var container, camera, scene, geometry, mesh, renderer, controls, particles, colors;
var objects = [];
// DOM element...
container = document.createElement('div');
document.body.appendChild(container);
// Camera...
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 0, 75);
// Scene...
scene = new THREE.Scene();
scene.add(camera);
// Renderer...
renderer = new THREE.WebGLRenderer({
clearAlpha: 1
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xffffff, 1);
document.body.appendChild(renderer.domElement);
// Scatter plot...
scatterPlot = new THREE.Object3D();
scene.add(scatterPlot);
// Make grid...
xzColor = 'black';
xyColor = 'black';
yzColor = 'black';
// Plot some random points...
circle = new THREE.CircleGeometry(5);
colors = [];
var max = 50;
var min = -50;
for (var i = 0; i < 10; i++) {
var object = new THREE.Mesh( circle, new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, opacity: 0.5 } ) );
object.position.x = Math.random() * (max - min) + min;
object.position.y = Math.random() * (max - min) + min;
object.position.z = 0;
scene.add( object );
objects.push( object );
}
animate();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
function onDocumentMouseDown( event ) {
event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( objects );
if ( intersects.length > 0 ) {
intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
intersects[ 0 ].object.geometry.setRadius(50);
var particle = new THREE.Sprite( particleMaterial );
particle.position.copy( intersects[ 0 ].point );
particle.scale.x = particle.scale.y = 16;
scene.add( particle );
}
}
Any idea how I can solve this? And where can I find the proper documentation?
Addendum:
I have used the following line of code:
intersects[ 0 ].object.geometry.scale(1.1,1.1,1.1);
In the code, and now the circles change their size. But ALL of them! I click on one circle, and every circle changes size. Does not make sense to me...
Don't scale your geometry. You're using the same geometry reference for all of your circles, so scaling one scales them all.
Instead, scale your Mesh, which is a unique object in the scene (even if it references the same geometry as other meshes). Much like how you're setting position for each Mesh, you also have access to scale:
intersects[0].object.scale.set(1.1, 1.1, 1.1);
That will scale the intersected Mesh object, and only that Mesh.
Cloning and creating a new Mesh is literally introducing a memory leak. The original Mesh won't go away until you remove it from the scene, and you keep making more and more Geometry objects as you clone the circle.
I have added a sphere and plane geometry to the scene when clicked on plane geometry it is linked to a website
now when hover on plane geometry the "mouse cursor" should change to "mouse pointer (hand)" and when not hovered
on plane geometry the mouse should retain its original style.
I tried using this statement "$('html,body').css('cursor','pointer');" but mouse cursor is not changing on
hovering, its changing when clicked on plane geometry and its cursor is not retaining to its original position.
can someone please help me how to solve the problem. I have also uploaded the code.
<html>
<head>
<body>
<script type="text/javascript" src="jquery-1.11.3.js"></script>
<script src ="./three.js-master/build/three.js"></script>
<script src ="./three.js-master/examples/js/controls/OrbitControls.js">
</script>
<script src ="./three.js-master/examples/js/renderers/Projector.js">
</script>
<script type="text/javascript" src="math.min.js"></script>
<script type="text/javascript">
window.onload = createsphere();
function createsphere()
{
var controls,scene,camera,renderer;
var planes = [];
var baseVector = new THREE.Vector3(0, 0, 1);
var camDir = new THREE.Vector3();
var planeLookAt = new THREE.Vector3();
function init()
{
var spriteResponse = [];
spriteResponse[0] = {ID:1, x: 0, y: 0};
spriteResponse[1] = {ID:2, x: 0, y: 0.1};
spriteResponse[2] = {ID:3, x: 0, y: 0.5};
spriteResponse[3] = {ID:4, x: 0.5, y: 0};
spriteResponse[4] = {ID:5, x: 0.25, y: 0.5 };
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
//camera.position.y = 1;
camera.position.z = 1 ;
var width = window.innerWidth;
var height = window.innerHeight;
renderer = new THREE.WebGLRenderer( {antialias:true} );
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
/* ------------------------ creating the geometry of sphere------------------------------*/
var radius = 2.5;
var spheregeometry = new THREE.SphereGeometry(radius, 20, 20, 0, -6.283, 1, 1);
//var texture = THREE.ImageUtils.loadTexture ('rbi00000083.jpg');
//texture.minFilter = THREE.NearestFilter;
//var spherematerial = new THREE.MeshBasicMaterial({map: texture});
var spherematerial = new THREE.MeshBasicMaterial({color: '#A9A9A9'});
var sphere = new THREE.Mesh(spheregeometry, spherematerial);
scene.add(sphere);
scene.add(camera);
scene.autoUpdate = true;
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.minPolarAngle = Math.PI/4;
controls.maxPolarAngle = 3*Math.PI/4;
for(var i=0; i<spriteResponse.length;i++)
{
//var spriteAlignment = new THREE.Vector2(0,0) ;
material_plane = new THREE.MeshBasicMaterial( {color: 0xffffff,side: THREE.DoubleSide } );
material_plane.needsUpdate = true;
//material.transparent=true;
geometry_plane = new THREE.PlaneGeometry(0.3, 0.2);
plane = new THREE.Mesh( geometry_plane, material_plane );
plane.database_id = spriteResponse[i].ID;
plane.LabelText = spriteResponse[i].name;
plane.position.set(spriteResponse[i].x,spriteResponse[i].y,-1);
scene.add(plane);
//plane.userData = { keepMe: true };
planes.push(plane);
//plane.id = cardinal.ID;
//var direction = camera.getWorldDirection();
camera.updateMatrixWorld();
var vector = camera.position.clone();
vector.applyMatrix3( camera.matrixWorld );
plane.lookAt(vector);
plane.userData = { URL: "http://stackoverflow.com"};
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
}
function onDocumentMouseDown( event )
{
//clearScene();
event.preventDefault();
var mouse = new THREE.Vector2();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( planes );
var matched_marker = null;
if(intersects.length != 0)
{
$('html,body').css('cursor','pointer');//mouse cursor change
for ( var i = 0; intersects.length > 0 && i < intersects.length; i++)
{
window.open(intersects[0].object.userData.URL);
}
}
else
$('html,body').css('cursor','cursor');//mouse cursor change
}//onDocumentMouseDown( event )
}
function animate()
{
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
init();
animate();
}
</script>
</body>
</head>
</html>
There are a number of ways to do it, but to keep it simple and make it easier for you to understand, my example includes a method that keeps with the format of the code you provided in your question.
I added a mousemove event to your init() function. The handler looks like this:
function onDocumentMouseMove(event) {
var mouse = new THREE.Vector2();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( planes );
if(intersects.length > 0) {
$('html,body').css('cursor', 'pointer');
} else {
$('html,body').css('cursor', 'default');
}
}
All this does is check whether or not one of your planes is intersected each time you move the mouse.
The reason this wasn't working before is because you only changed the cursor on mouse-down which won't give the desired 'hover' effect.
Here's a working fiddle. Just note that I've commented out any controls related code to get the fiddle working quicker, it won't change the solution.
You can't change hover state within JS as stated here:
https://stackoverflow.com/a/11371599/5001964
I think easiest solution would be to make it with css:
body:hover {
cursor: pointer;
}
Although it would be better if instead body you choose a specific DOM node to make the hover effect.
I am Trying to create an interactive Sphere with JavaScript for an assignment for HCI, the problem is that I am a novice to JavaScript and Three.js.
what I am after is to make it so when the sphere is clicked on that it displays the statistics of a specific subject. I have created the sphere and made it into an object but I am having trouble with the interaction of the sphere. I don't care if a div or a alert opens when the sphere is clicked on but I just need it to work as a dummy version
below is an example in JavaScript and THREE.js:
var sphere = new Object({}); //declared sphere as an object first.
var angularSpeed = 0.2;
var lastTime = 0;
function animate (){
//update
var time = (new Date()).getTime();
var timeDiff = time - lastTime;
var angleChange = angularSpeed * timeDiff * 0.1 * Math.PI / 1000;
sphere.rotation.y -= angleChange;
sphere2.rotation.sphere -=angleChange;
lastTime = time;
// render
renderer.render(scene, camera);
requestAnimationFrame(function(){ //request new frame
animate();
});
}
// renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// camera
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 500;
// scene
var scene = new THREE.Scene();
//material
var material = new THREE.MeshLambertMaterial({
map:THREE.ImageUtils.loadTexture('images/earth2.jpg')});
//sphere geometry
sphere = new THREE.Mesh(new THREE.SphereGeometry( 100, 50, 50 ), material);
sphere.overdraw = true;
sphere.rotation.x = Math.PI * 0.1;
sphere.position.x= 0; // moves position horizontally (abscissa) + = right and - = left
sphere.position.y= 0; // moves position virtually (ordinate) + = right and - = left
sphere.position.z= 0; // moves position z (applicate) + = forwards and - = backwards
scene.add(sphere);
//animate
animate();
var sphere = new Object:({event});
function statistics(){
alert('You clicked on the div!') // displays the statistics before the rendering
};
sphere.onMouseDown=statistics(event);
.onMouseDown is only available for HTML element. You can't use this function for THREE.js objects, but Raycaster is exactly what you want!
jsfiddle
var container, stats;
var camera, scene, projector, raycaster, renderer, selected, sphere;
var mouse = new THREE.Vector2(), INTERSECTED;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
scene = new THREE.Scene();
var light = new THREE.DirectionalLight( 0xffffff, 2 );
light.position.set( 1, 1, 1 ).normalize();
scene.add( light );
var light = new THREE.DirectionalLight( 0xffffff );
light.position.set( -1, -1, -1 ).normalize();
scene.add( light );
sphere = new THREE.Mesh(new THREE.SphereGeometry( 20, 50, 50 ), new THREE.MeshNormalMaterial());
sphere.overdraw = true;
scene.add(sphere);
projector = new THREE.Projector();
raycaster = new THREE.Raycaster();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor( 0xf0f0f0 );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
window.addEventListener( 'resize', onWindowResize, false );
renderer.domElement.addEventListener( 'mousedown', onCanvasMouseDown, false);
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.lookAt(new THREE.Vector3(0,0,0));
camera.position = new THREE.Vector3(0,100,100);
// find intersections
var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
projector.unprojectVector( vector, camera );
raycaster.set( camera.position, vector.sub( camera.position ).normalize() );
selected = raycaster.intersectObjects( scene.children );
renderer.render( scene, camera );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
//detect mouse click on the sphere
function onCanvasMouseDown( event ){
if(selected[0].object==sphere){
statistics();
}
}
function statistics(){
alert('You clicked on the div!') // displays the statistics before the rendering
};