I've looked for help of first player rotation on three.js for a while but most of the answers are outdated with functions which currently don't exist in the updated library.
I'm trying to make my code run so that the camera will rotate around it's own axis according to the position of the mouse on the screen.
The current rotation code is:
var scale = 10;
function viewKeys(){
document.addEventListener("mousemove", MouseMove, true);
function MouseMove(event) {
mouseX = event.clientX - divOffsetWidth;
mouseY = event.clientY - divOffsetHeight;
}
}
divOffset variables make the mouse positions read relative to the center of the HTML div.
function viewAnimate(){
camera.rotation.x = -((3/2)*(Math.PI*mouseY)) / (scale);
camera.rotation.y = -(2*(Math.PI*mouseX)) / (scale);
}
The viewKeys() function is called in the init() function and the viewAnimate() function is called within the animate() function.
Currently the code can rotate normally when the camera's position is (0,0,0) but if I move to a different position it looks as if the camera is rotating relative to the whole environment's axis.
I am aware that there are lots of control librarys for three.js but I would like to understand how to be able to rotate something on its own axis myself.
How do you suppose I change the rotation so that it works correctly?
If you want to rotate the camera yourself via the mouse, you will have to understand how Euler rotations work in three.js. See this answer.
One way to implement what you want is by using a pattern like so:
var scale = 1;
var mouseX = 0;
var mouseY = 0;
camera.rotation.order = "YXZ"; // this is not the default
document.addEventListener( "mousemove", mouseMove, false );
function mouseMove( event ) {
mouseX = - ( event.clientX / renderer.domElement.clientWidth ) * 2 + 1;
mouseY = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
camera.rotation.x = mouseY / scale;
camera.rotation.y = mouseX / scale;
}
I agree with you that experimenting with this would be a good learning experience.
three.js r.89
Three.js : rev 73
I'm using the following construct to find intersection of mouse click with objects in the 3d world (orthographic setup):
function onDocumentMouseDown(event) {
event.preventDefault();
console.log("Click");
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();
// update the picking ray with the camera and mouse position
raycaster.setFromCamera(mouse, camera);
// calculate objects intersecting the picking ray
var intersects = raycaster.intersectObjects(scene.children);
console.log("intersects: " + intersects.length);
for (var i = 0; i < intersects.length; i++) {
console.log(intersects[i].point);
}
}
However, the intersection is very inaccurate. Intersection is captured when I click near the top left of the box only.
jsFiddle: Can someone please help me understand why is this misbehaving ?
Also, if no object is being selected, I want to find out where is the click in 3d world relative to the box - left, right, below the box ? Can I use the ray itself to compute this ?
you have to get accurate mouse position for ray-casting :-
mouse.x = ( (event.clientX -renderer.domElement.offsetLeft) / renderer.domElement.width ) * 2 - 1;
mouse.y = -( (event.clientY - renderer.domElement.offsetTop) / renderer.domElement.height ) * 2 + 1;
you have to fire event listener when window resize
i update the fiddle again check it now .
add new function for window resize...
code is self explaintory ...hope you got it .
Check Update Fiddle now
updated fiddle :-
http://jsfiddle.net/gc1v0rza/5/
I have these event listeners in my code
canvas.addEventListener('mousemove', onMouseMove, false);
canvas.addEventListener('mousedown', onMouseDown,false);
canvas.addEventListener('mouseup', onMouseUp, false);
These functions will help me to pan the canvas. I have declared a variable in the onLoad called pan, isDown, mousePostion and previous mouse positions. Then in the initialise function is set the pan,mousePos and premousepos to vectors containing 0,0
function draw() {
context.translate(pan.getX(), pan.getY());
topPerson.draw(context);
console.log(pan);
}
function onMouseDown(event) {
var x = event.offsetX;
var y = event.offsetY;
var mousePosition = new vector(event.offsetX, event.offsetY);
previousMousePosition = mousePosition;
isDown = true;
console.log(previousMousePosition);
console.log("onmousedown" + "X coords: " + x + ", Y coords: " + y);
}
function onMouseUp(event) {
isDown = false;
}
function onMouseMove(event) {
if (isDown) {
console.log(event.offsetX);
mousePosition = new vector(event.offsetX, event.offsetY);
newMousePosition = mousePosition;
console.log('mouseMove' + newMousePosition);
var panX = newMousePosition.getX() - previousMousePosition.getX();
var panY = newMousePosition.getY() - previousMousePosition.getY();
console.log('onMouseMove: ' + panX);
pan = new vector(panX, panY);
console.log('mouseMove' + pan);
}
}
But it is not registering the new pan Values so you could attempt to drag the canvas. I know my mouse dragging events work but is just doesnt pan.
Here's a simple (annotated) example of panning code
It works by accumulating the net amount the mouse has been dragged horizontally (and vertically) Then it redraws everything, but offset by those accumulated horizontal & vertical distances.
Example code and a Demo:
// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// account for scrolling
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
// mouse drag related variables
var isDown=false;
var startX,startY;
// the accumulated horizontal(X) & vertical(Y) panning the user has done in total
var netPanningX=0;
var netPanningY=0;
// just for demo: display the accumulated panning
var $results=$('#results');
// draw the numbered horizontal & vertical reference lines
for(var x=0;x<100;x++){ ctx.fillText(x,x*20,ch/2); }
for(var y=-50;y<50;y++){ ctx.fillText(y,cw/2,y*20); }
// listen for mouse events
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// calc the starting mouse X,Y for the drag
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// set the isDragging flag
isDown=true;
}
function handleMouseUp(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// clear the isDragging flag
isDown=false;
}
function handleMouseOut(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// clear the isDragging flag
isDown=false;
}
function handleMouseMove(e){
// only do this code if the mouse is being dragged
if(!isDown){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// get the current mouse position
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// dx & dy are the distance the mouse has moved since
// the last mousemove event
var dx=mouseX-startX;
var dy=mouseY-startY;
// reset the vars for next mousemove
startX=mouseX;
startY=mouseY;
// accumulate the net panning done
netPanningX+=dx;
netPanningY+=dy;
$results.text('Net change in panning: x:'+netPanningX+'px, y:'+netPanningY+'px');
// display the horizontal & vertical reference lines
// The horizontal line is offset leftward or rightward by netPanningX
// The vertical line is offset upward or downward by netPanningY
ctx.clearRect(0,0,cw,ch);
for(var x=-50;x<50;x++){ ctx.fillText(x,x*20+netPanningX,ch/2); }
for(var y=-50;y<50;y++){ ctx.fillText(y,cw/2,y*20+netPanningY); }
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4 id=results>Drag the mouse to see net panning in x,y directions</h4>
<canvas id="canvas" width=300 height=150></canvas>
To answer question
You have not provided some of the code. Specifically the vector object you are creating each event, could be there. (really you should not be creating a new object each time. Create once and update the values)
What I do see is that mouseMove events do not update the previous mouse position object so you will only get panning from the last mouse down. But you may want that. So without the code I don't know what is wrong as the code given is OK.
Below is how I do the whole shabang..
How to pan (and zoom).
Below is an example of panning and zooming with the mouse. Its a little more complex than standard pan and zooms, that is because I have added some smoothing to the pan and zoom to give it a better interactive feel.
How it works.
The canvas uses a transformation matrix to transform points. What this does is maintain that matrix. I call the transformed space, real space. I also maintain an inverse matrix, that is used to convert from screen space into real space.
The core of the demo is around the object displayTransform it holds the matrix, all the individual values needed, and the functions update() call once a frame, setHome() get the screen space transform and applies it to the canvas. Used to clear the screen. And setTransform() this set the canvas to real space (the zoomed panned space)
To smooth out movements I have a mirror of the values x, y, ox, oy, scale, and rotate. ((ox,oy) are origin x and y) (and yes rotate works) each of these variable has a delta prefixed with d and a chaser prefixed with c. The chaser values chase the required values. You should not touch the chaser values. There are two values called drag and accel (short for acceleration) drag (not real simulated drag) is how quickly the deltas decay. Values for drag > 0.5 will result in a bouncy response. As you get toward one it will get more and more bouncy. At 1 the bound will not stop, above one and it's unusable. 'accel' is how quickly the transform responds to mouse movement. Low values are slow response, 0 is no response at all, and one is instant response. Play with the values to find what you like.
Example of the logic for chaser values
var x = 100; // the value to be chased
var dx = 0; // the delta x or the change in x per frame
var cx = 0; // the chaser value. This value chases x;
var drag = 0.1; // quick decay
var accel = 0.9; // quick follpw
// logic
dx += (x-cx)*accel; // get acceleration towards x
dx *= drag; // apply the drag
cx += dx; // change chaser by delta x.
Convert coords
No point having a zoom panned rotated canvas if you don't know where things are. To do this I keep an inverse matrix. It converts screen x and y into realspace x and y. For convenience I convert the mouse to real space every update. If you want the reverse realSpace to screen space. then its just
var x; // real x coord (position in the zoom panned rotate space)
var y; // real y coord
// "this" is displayTransform
x -= this.cx;
y -= this.cy;
// screenX and screen Y are the screen coordinates.
screenX = (x * this.matrix[0] + y * this.matrix[2])+this.cox;
screenY = (x * this.matrix[1] + y * this.matrix[3])+this.coy;
You can see it at the end of the mouse displayTransform.update where I use the inverse transform to convert the mouse screen coords to real coords. Then in the main update loop I use the mouse real coords to display the help text. I leave it up to the user of the code to create a function that will convert any screen coord. (easy just pinch the bit where the mouse is being converted).
Zoom
The zoom is done with the mouse wheel. This presents a bit of a problem and naturally you expect the zoom to be centered on the mouse. But the transform is actually relative to the top left of the screen. To fix this I also keep an origin x and y. This basically floats about until the wheel zoom is needed then it is set to the mouse real position, and the mouse distance from the top left is placed in the transform x and y position. Then just increase or decrease the scale to zoom in and out. I have left the origin and offset to float (not set the chase values) this works for the current drag and acceleration setting but if you notice that it's not working that well with other setting set the the cx, cy, cox, coy values as well. ( I have added a note in the code)
Pan
Pan is done with the left mouse button. Click and drag to pan. This is straight forward. I get the difference between the last mouse position and the new one screen space (the coords given by the mouse events) This gives me a mouse delta vector. I transform the delta mouse vector into real space and subtract that from the top left coords displayTransform.x and displayTransform.y. Thats it I let the chaser x and y smooth it all out.
The snippet just displays a large image that can be panned and zoomed. I check for the complete flag rather than use onload. While the image is loading the snippet will just display loading. The main loop is refreshed with requestAnimationFrame, first I update the displayTransform then the canvas is cleared in home space (screen space) and then the image is displayed in real space. As always I a fighting time so will return as time permits to add more comments, and maybe a function or two.
If you find the chase variables a little to much, you can just remove them and replace all the c prefixed vars with the unprefixed ones.
OK hope this helps. Not done yet as need to clean up but need to do some real work for a bit.
var canvas = document.getElementById("canV");
var ctx = canvas.getContext("2d");
var mouse = {
x : 0,
y : 0,
w : 0,
alt : false,
shift : false,
ctrl : false,
buttonLastRaw : 0, // user modified value
buttonRaw : 0,
over : false,
buttons : [1, 2, 4, 6, 5, 3], // masks for setting and clearing button raw bits;
};
function mouseMove(event) {
mouse.x = event.offsetX;
mouse.y = event.offsetY;
if (mouse.x === undefined) {
mouse.x = event.clientX;
mouse.y = event.clientY;
}
mouse.alt = event.altKey;
mouse.shift = event.shiftKey;
mouse.ctrl = event.ctrlKey;
if (event.type === "mousedown") {
event.preventDefault()
mouse.buttonRaw |= mouse.buttons[event.which-1];
} else if (event.type === "mouseup") {
mouse.buttonRaw &= mouse.buttons[event.which + 2];
} else if (event.type === "mouseout") {
mouse.buttonRaw = 0;
mouse.over = false;
} else if (event.type === "mouseover") {
mouse.over = true;
} else if (event.type === "mousewheel") {
event.preventDefault()
mouse.w = event.wheelDelta;
} else if (event.type === "DOMMouseScroll") { // FF you pedantic doffus
mouse.w = -event.detail;
}
}
function setupMouse(e) {
e.addEventListener('mousemove', mouseMove);
e.addEventListener('mousedown', mouseMove);
e.addEventListener('mouseup', mouseMove);
e.addEventListener('mouseout', mouseMove);
e.addEventListener('mouseover', mouseMove);
e.addEventListener('mousewheel', mouseMove);
e.addEventListener('DOMMouseScroll', mouseMove); // fire fox
e.addEventListener("contextmenu", function (e) {
e.preventDefault();
}, false);
}
setupMouse(canvas);
// terms.
// Real space, real, r (prefix) refers to the transformed canvas space.
// c (prefix), chase is the value that chases a requiered value
var displayTransform = {
x:0,
y:0,
ox:0,
oy:0,
scale:1,
rotate:0,
cx:0, // chase values Hold the actual display
cy:0,
cox:0,
coy:0,
cscale:1,
crotate:0,
dx:0, // deltat values
dy:0,
dox:0,
doy:0,
dscale:1,
drotate:0,
drag:0.1, // drag for movements
accel:0.7, // acceleration
matrix:[0,0,0,0,0,0], // main matrix
invMatrix:[0,0,0,0,0,0], // invers matrix;
mouseX:0,
mouseY:0,
ctx:ctx,
setTransform:function(){
var m = this.matrix;
var i = 0;
this.ctx.setTransform(m[i++],m[i++],m[i++],m[i++],m[i++],m[i++]);
},
setHome:function(){
this.ctx.setTransform(1,0,0,1,0,0);
},
update:function(){
// smooth all movement out. drag and accel control how this moves
// acceleration
this.dx += (this.x-this.cx)*this.accel;
this.dy += (this.y-this.cy)*this.accel;
this.dox += (this.ox-this.cox)*this.accel;
this.doy += (this.oy-this.coy)*this.accel;
this.dscale += (this.scale-this.cscale)*this.accel;
this.drotate += (this.rotate-this.crotate)*this.accel;
// drag
this.dx *= this.drag;
this.dy *= this.drag;
this.dox *= this.drag;
this.doy *= this.drag;
this.dscale *= this.drag;
this.drotate *= this.drag;
// set the chase values. Chase chases the requiered values
this.cx += this.dx;
this.cy += this.dy;
this.cox += this.dox;
this.coy += this.doy;
this.cscale += this.dscale;
this.crotate += this.drotate;
// create the display matrix
this.matrix[0] = Math.cos(this.crotate)*this.cscale;
this.matrix[1] = Math.sin(this.crotate)*this.cscale;
this.matrix[2] = - this.matrix[1];
this.matrix[3] = this.matrix[0];
// set the coords relative to the origin
this.matrix[4] = -(this.cx * this.matrix[0] + this.cy * this.matrix[2])+this.cox;
this.matrix[5] = -(this.cx * this.matrix[1] + this.cy * this.matrix[3])+this.coy;
// create invers matrix
var det = (this.matrix[0] * this.matrix[3] - this.matrix[1] * this.matrix[2]);
this.invMatrix[0] = this.matrix[3] / det;
this.invMatrix[1] = - this.matrix[1] / det;
this.invMatrix[2] = - this.matrix[2] / det;
this.invMatrix[3] = this.matrix[0] / det;
// check for mouse. Do controls and get real position of mouse.
if(mouse !== undefined){ // if there is a mouse get the real cavas coordinates of the mouse
if(mouse.oldX !== undefined && (mouse.buttonRaw & 1)===1){ // check if panning (middle button)
var mdx = mouse.x-mouse.oldX; // get the mouse movement
var mdy = mouse.y-mouse.oldY;
// get the movement in real space
var mrx = (mdx * this.invMatrix[0] + mdy * this.invMatrix[2]);
var mry = (mdx * this.invMatrix[1] + mdy * this.invMatrix[3]);
this.x -= mrx;
this.y -= mry;
}
// do the zoom with mouse wheel
if(mouse.w !== undefined && mouse.w !== 0){
this.ox = mouse.x;
this.oy = mouse.y;
this.x = this.mouseX;
this.y = this.mouseY;
/* Special note from answer */
// comment out the following is you change drag and accel
// and the zoom does not feel right (lagging and not
// zooming around the mouse
/*
this.cox = mouse.x;
this.coy = mouse.y;
this.cx = this.mouseX;
this.cy = this.mouseY;
*/
if(mouse.w > 0){ // zoom in
this.scale *= 1.1;
mouse.w -= 20;
if(mouse.w < 0){
mouse.w = 0;
}
}
if(mouse.w < 0){ // zoom out
this.scale *= 1/1.1;
mouse.w += 20;
if(mouse.w > 0){
mouse.w = 0;
}
}
}
// get the real mouse position
var screenX = (mouse.x - this.cox);
var screenY = (mouse.y - this.coy);
this.mouseX = this.cx + (screenX * this.invMatrix[0] + screenY * this.invMatrix[2]);
this.mouseY = this.cy + (screenX * this.invMatrix[1] + screenY * this.invMatrix[3]);
mouse.rx = this.mouseX; // add the coordinates to the mouse. r is for real
mouse.ry = this.mouseY;
// save old mouse position
mouse.oldX = mouse.x;
mouse.oldY = mouse.y;
}
}
}
// image to show
var img = new Image();
img.src = "https://upload.wikimedia.org/wikipedia/commons/e/e5/Fiat_500_in_Emilia-Romagna.jpg"
// set up font
ctx.font = "14px verdana";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
// timer for stuff
var timer =0;
function update(){
timer += 1; // update timere
// update the transform
displayTransform.update();
// set home transform to clear the screem
displayTransform.setHome();
ctx.clearRect(0,0,canvas.width,canvas.height);
// if the image loaded show it
if(img.complete){
displayTransform.setTransform();
ctx.drawImage(img,0,0);
ctx.fillStyle = "white";
if(Math.floor(timer/100)%2 === 0){
ctx.fillText("Left but to pan",mouse.rx,mouse.ry);
}else{
ctx.fillText("Wheel to zoom",mouse.rx,mouse.ry);
}
}else{
// waiting for image to load
displayTransform.setTransform();
ctx.fillText("Loading image...",100,100);
}
if(mouse.buttonRaw === 4){ // right click to return to homw
displayTransform.x = 0;
displayTransform.y = 0;
displayTransform.scale = 1;
displayTransform.rotate = 0;
displayTransform.ox = 0;
displayTransform.oy = 0;
}
// reaquest next frame
requestAnimationFrame(update);
}
update(); // start it happening
.canC { width:400px; height:400px;}
div {
font-size:x-small;
}
<div>Wait for image to load and use <b>left click</b> drag to pan, and <b>mouse wheel</b> to zoom in and out. <b>Right click</b> to return to home scale and pan. Image is 4000 by 2000 plus so give it time if you have a slow conection. Not the tha help text follows the mouse in real space. Image from wiki commons</div>
<canvas class="canC" id="canV" width=400 height=400></canvas>
I've created a near exact implementation of the Three.js Draggable Cubes example, except that my implementation ignores the z axis for movement in 2D. The example can be found here: http://threejs.org/examples/#webgl_interactive_draggablecubes
While I am able to click and move around my object, if I move the mouse too fast, the object will lag behind; the mouse pointer will move to it's location and then the object will follow the mouses path to the location. This issue is also noticeable in the Three.js example. Try dragging one of the cubes at anything beyond a moderate speed.
I've tried a few things to get the object to be directly under the mouse pointer but none have worked. The closest I think I might have come to a solution was by changing the mouse position update in the MouseMove event. However, it appears that the Three.js implementation of the code returns values between 1 and -1 rather than the screen X and Y coordinates, which leads me to wonder if the original implementation is causing the lag.
//Original Implementation - Works With Lag
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
console.log(mouse.x + "," + mouse.y); //Output: -0.9729166666666667,0.8596858638743455
//My Implementation - Does Not Work
mouse.x = event.clientX - (window.innerWidth / 2);
mouse.y = event.clientY - (window.innerHeight / 2);
console.log(mouse.x + "," + mouse.y); //Output: -934,-410.5
//Update Function
void Update()
{
var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
var intersects = raycaster.intersectObject(plane);
meshToMove.position.x = intersects[0].point.x;
meshToMove.position.y = intersects[0].point.y;
}
//Main Loop
function Loop()
{
Update();
Render();
requestAnimationFrame(Loop);
}
Q: How can I update the three.js Draggable Cubes example so that objects don't lag behind the mouse during a click and drag?
I'm using kineticjs to draw some widget on a canvas. This widget is 600px wide and is composed of several rectangles (24 by default). On this rectangles an other one can be dragged, let's call it "cursor".
Instead of a smooth drag, i want the cursor to jump to the other rectangles only when my mouse is far enough (like a stepped drag if you prefer).
For example if the cursor is at 0,0 and i have a total of 24 rectangles , i want my cursor to move to the next rectangle only when my mouse is at 25,0 (600px / 24 rectangles = 25px).
So to do that i have implemented :
cursor.setDragBoundFunc(function(pos){
var caseSize = WIDTH / caseNum;
var posX = Math.round(pos.x/caseNum) * caseSize;
if(posX > (WIDTH - caseSize)) {
posX = WIDTH - caseSize;
}
if(posX < 0 ) {
posX = 0;
}
return {
x: posX,
y: cursor.getAbsolutePosition().y
}
});
The problem is pos.x does not represent the mouse position in the canvas but the mouse position from the start of the drag event (pos will be 0,0 even if i start dragging from middle of the canvas).
Here a example of the problem : http://jsfiddle.net/H9rpz/
How can i get the mouse position in the canvas in setDragBoundFunc() ?
Thanks
This exact feature has been implemented in a KineticJS manual test. Here's the code you're looking for:
https://github.com/ericdrowell/KineticJS/blob/master/tests/js/manualTests.js#L1004
Give it a try :)
It seems the setDragBoundFunc function accepts two arguments and the second is an event object that might contain what you're after:
cursor.setDragBoundFunc(function(pos, event){
var posX = event.offsetX;
....
});
You also have a math logic error at the beginning of the function. It should read:
cursor.setDragBoundFunc(function(pos, event){
var caseSize = WIDTH / caseNum;
var posX = event.offsetX;
posX = Math.floor(posX / caseSize) * caseSize; // This right here
...
});
Working example:
http://jsfiddle.net/H9rpz/3/
In addition to #Jan's answer, your math is a bit off:
cursor.setDragBoundFunc(function(pos, event){
var posX = event.offsetX;
posX = Math.floor(posX/WIDTH * caseNum) * caseWidth;
...