three.js how to draw line with mousedown event - javascript

I have try a lot of ways to complete this effect,i want to draw a line of mouse down event,and i have seen many other questions but do not have any idea about it,so far i use the Ray caster method of intersectObjects() and get the position of the click,but i do not how to then,Hope someone give me advice,thanks very much.
Here are part of mine code:
event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = -( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
var raycaster=new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects,true);
console.log(intersects[0].point);//type of intersects[0] is object,one of attribute is point?
yesterday i write some codes and have complete part of my effect. Here are some code:
var clickCount = 0;//initial value
clickCount = clickCount+1;
if(intersects.length>0)
{
switch(clickCount)
{
case 1:
var startPoint=intersects[0].point;//store the first intersect point when the first click
break;
case 2:
var endPoint =intersects[0].point;//store the second intersect point when the second click
break;
}
}
clickCount=1;
var geometry = new THREE.Geometry();
material = new THREE.LineBasicMaterial({color:0xffffff,linewidth:2});
geometry.vertices.push(startPoint);
geometry.vertices.push(endPoint);
line = new THREE.Line(geometry, material);
scene.add(line);
but this is not the final effect what i wanted.this segment lines are all rays set up from the vector(0,0,0). here is the screenshot:
the red line is the effect what i want to implementate. Could anyone figure out the reason?thanks very much.

It's better to remember the first clicked object, then on the next click you will check, if it's the same object or another one, and if it's another one, then draw a line between them.
var intersected, lineObjects = [],
objects = [];
. . .
and in the event handler:
if (intersects.length > 0) {
var found = intersects[0].object;
if (found != intersected) {
if (lineObjects.length > 0) {
var line = lineObj(lineObjects[0].position, found.position);
scene.add(line);
lineObjects[0].material.color.setHex(lineObjects[0].userData.oldColor);
intersected = null;
lineObjects = [];
} else {
found.userData.oldColor = found.material.color.getHex();
found.material.color.set(0x00FF00);
intersected = found;
lineObjects.push(found);
}
} else {
found.material.color.setHex(found.userData.oldColor);
intersected = null;
lineObjects = [];
}
}
I've made a jsfiddle example. Look at onMouseDown() function. All the things I described above are there.

Related

Three.js performance very slow using onMouseMove with RayCaster

I'm building an application in three.js, however I'm having real problems with performance. This part of the application is based upon the Voxel Painter example. In my version, the user clicks on a cell to begin placement, drags the cursor to where they wish to end placement, and clicks to end.
function onDocumentMouseMove(event) {
//set up mouse and raycaster
event.preventDefault();
mouse.set((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1);
raycaster.setFromCamera(mouse, camera);
switch (buildMode) {
case buildModes.CORRIDOR:
scene.add(rollOverFloor);
var intersects = raycaster.intersectObjects(gridObject);
if (intersects.length > 0) {
var intersect = intersects[0];
if (beginPlace == true) {
//store the intersection position
var endPlace = new THREE.Vector3(0, 0, 0);
endPlace.copy(intersect.point).add(intersect.face.normal);
endPlace.divideScalar(step).floor().multiplyScalar(step).addScalar(step / step);
endPlace.set(endPlace.x, 0, endPlace.z);
corridorDrag(endPlace);
}
//if user hasn't begun to place the wall
else {
//show temporary wall on grid
rollOverFloor.position.copy(intersect.point).add(intersect.face.normal);
rollOverFloor.position.divideScalar(step).floor().multiplyScalar(step).addScalar(step / step);
rollOverFloor.position.set(rollOverFloor.position.x, 0, rollOverFloor.position.z);
}
}
break;
}
render();
}
The code above is called when the user moves the mouse (there are many buildmodes in the main application, but I have not included them here). This function simply gets a start and end point, the corridorDrag() function fills in the cells between the start and end points:
function corridorDrag(endPlace) {
deleteFromScene(stateType.CORRIDOR_DRAG);
var startPoint = startPlace;
var endPoint = endPlace;
var zIntersect = new THREE.Vector3(startPoint.x, 0, endPoint.z);
var xIntersect = new THREE.Vector3(endPoint.x, 0, startPoint.z);
var differenceZ = Math.abs(startPlace.z - zIntersect.z);
var differenceX = Math.abs(startPlace.x - xIntersect.x);
var mergedGeometry = new THREE.Geometry();
for (var i = 0; i <= (differenceZ / step); i++) {
for (var j = 0; j <= (differenceX / step); j++) {
var x = startPlace.x;
var y = startPlace.y;
var z = startPlace.z;
if (endPoint.x <= (startPlace.x )) {
if (endPoint.z <= (startPlace.z)) {
x = x - (step * j);
z = z - (step * i);
}
else if (endPoint.z >= (startPlace.z)) {
x = x - (step * j);
z = z + (step * i);
}
} else if (endPoint.x >= (startPlace.x)) {
if (endPoint.z <= (startPlace.z)) {
x = x + (step * j);
z = z - (step * i);
}
else if (endPoint.z >= (startPlace.z)) {
x = x + (step * j);
z = z + (step * i);
}
}
floorGeometry.translate(x, y, z);
mergedGeometry.merge(floorGeometry);
floorGeometry.translate(-x, -y, -z);
}
}
var voxel = new THREE.Mesh(mergedGeometry, tempMaterial);
voxel.state = stateType.CORRIDOR_DRAG;
scene.add(voxel);
tempObjects.push(voxel);
}
Firstly, the deleteFromScene() function removes all current highlighted cells from the scene (see below). The code then (I believe), should create a number of meshes, depending on the start and end points, and add them to the scene.
function deleteFromScene(state) {
tempObjects = [];
var i = scene.children.length;
while (i--) {
if (scene.children[i].state != undefined)
if (scene.children[i].state == state)
scene.children.splice(i, 1);
}
}
As I said, it is very, very slow. It also appears to be adding an obscene amount of vertices to the renderer, as seen in the WebGLRenderer stats window. I have no idea why it's adding so many vertices, but I'm assuming that's why it's rendering so slowly.
The application can be viewed here - the problem can be seen by clicking on one cell, dragging the cursor to the other end of the grid, and observing the time taken to fill in the cells.
Thank you in advance, this really is a last resort.
A few years ago Twitter put out an update. In this update they had just introduced infinite scrolling and on the day of its release the update was crashing users browsers. Twitter engineers did some investigating and found that the crashes were the result of the scroll event firing hundreds of times a second.
Mouse events can fire many MANY times a second and can cause your code to execute too often, which slows down the browser and (in many cases) crashes it. The solution for Twitter (and hopefully you) was simple: Poll your event.
Inside your mousemove event handler check that it has been some number of milliseconds since the last move event.
var lastMove = Date.now();
function onDocumentMouseMove(event) {
if (Date.now() - lastMove < 31) { // 32 frames a second
return;
} else {
lastMove = Date.now();
}
// your code here
}
I hope that helps!

KineticJS - Swapping shape positions upon contact/mousemove trigger

I'm using KineticJS and trying to get something done that seems simple enough: trying to get a shape to change position with the shape that's currently being dragged.
The idea is that:
• You pick up a shape on the canvas. This triggers a mousedown event listener, which saves the current position of the shape you've picked up.
• While holding the shape, if you trigger the mouseover on another shape, that shape's event gets triggered and swaps its position, based on the current shape's saved position.
Here is the relevant code I've written to try to get that working:
Board setup:
Simply just setting up the board and calling the needed functions here. I'm not doing anything with the stage, gameBoard, or ctx yet (part of it was for when I tried to get drawImage to work on multiple canvases, but have abandoned that for now).
class BoardView {
constructor(stage, gameBoard, ctx) {
this.stage = stage;
this.gameBoard = gameBoard;
this.ctx = ctx;
this.orbs = [[], [], [], [], []];
this.setupBoard();
}
Board setup functions:
This is where I go about setting up the board and giving each Kinetic Circle the attributes it needs to render on the Layer. Maybe I'm missing something obvious here?
setupBoard () {
for (let colIdx = 0; colIdx < 5; colIdx++) {
this.addRow(colIdx);
}
this.renderBoard();
}
addRow (colIdx) {
for (let rowIdx = 0; rowIdx < 6; rowIdx++) {
let orbType = Math.round(Math.random() * 5);
let orbColor;
if (orbType === 0) {
orbColor = "#990000";
} else if (orbType === 1) {
orbColor = "#112288";
} else if (orbType === 2) {
orbColor = "#005544";
} else if (orbType === 3) {
orbColor = "#776611";
} else if (orbType === 4) {
orbColor = "#772299";
} else {
orbColor = "#dd2277";
}
let orbject = new Kinetic.Circle({
x: (rowIdx + 0.5) * 100,
y: (colIdx + 0.5) * 100,
width: 100,
height: 100,
fill: orbColor,
draggable: true
});
this.orbs[colIdx].push(orbject);
}
}
Board render function:
This is where I add all the Kinetic Circle objects into new layers, and give those layers all its own attributes to work with when I call the event handlers. I also set up the event handlers here after adding the layers to the stage. Am I perhaps messing this up by adding too many layers?
renderBoard () {
for (let row = 0; row < this.orbs.length; row++) {
for (let orb = 0; orb < this.orbs[row].length; orb++) {
let layer = new Kinetic.Layer();
layer.add(this.orbs[row][orb]);
layer.moving = false;
layer.orbId = `orb${row}${orb}`;
layer.pos = [this.orbs[row][orb].attrs.x, this.orbs[row][orb].attrs.y];
this.stage.add(layer);
layer.on("mousedown", this.handleMouseDown);
layer.on("mouseup", this.handleMouseUp);
layer.on("mouseout", this.handleMouseOut);
layer.on("mousemove", this.handleMouseMove);
}
}
}
Mouse event handlers:
This is where I think I'm having my main problem. How I handle the event of moving the mouse to change orbs, perhaps I'm doing something terribly wrong?
handleMouseDown (e) {
window.currentOrb = this;
console.log(window.currentOrb.orbId);
this.moving = true;
}
//handleMouseUp (e) {
// window.currentOrb = undefined;
// this.moving = false;
//}
//handleMouseOut (e) {
//}
handleMouseMove (e) {
if (window.currentOrb !== undefined && window.currentOrb.orbId != this.orbId) {
this.children[0].attrs.x = window.currentOrb.pos[0];
this.children[0].attrs.y = window.currentOrb.pos[1];
this.children[0].draw();
} else {
}
}
}
module.exports = BoardView;
I've tried looking at the KineticJS docs and many StackOverflow answers as I could in hopes of finding a solution that would work for me, but nothing I've seen and tried so far (including the suggestions that came up as I wrote this question) seemed to be of help, and I'm aware the way I've gone about this so far is probably far from the best way to accomplish what I want, so I'm open to any suggestions, pointers, answered questions, or whatever can point me in the right direction to what I'm missing in order to get this to work.
In case this is helpful, here is also a visualization of how things look when the board is rendered.
The circles are all Kinetic Circles (orbs for the purpose of what I'm going for), and clicking and dragging one to another, the one that isn't being dragged but hovered over should move to the original position of the dragged circles.
Thanks!
EDIT:
I made a few changes to the code since then. First off, I changed adding many layers to the stage, to just one:
renderBoard () {
let layer = new Kinetic.Layer();
for (let row = 0; row < this.orbs.length; row++) {
for (let orb = 0; orb < this.orbs[row].length; orb++) {
layer.add(this.orbs[row][orb]);
this.orbCanvases.push(orbCanvas.id);
}
}
this.stage.add(layer);
}
I instead added listeners to the orb objects instead:
addRow (colIdx) {
for (let rowIdx = 0; rowIdx < 6; rowIdx++) {
//same code as before
let orbject = new Kinetic.Circle({
x: (rowIdx + 0.5) * 100, y: (colIdx + 0.5) * 100,
width: 100, height: 100,
fill: orbColor, draggable: true, pos: [rowIdx, colIdx]
});
orbject.on("mousedown", this.handleMouseDown);
orbject.on("mouseup", this.handleMouseUp);
orbject.on("mouseout", this.handleMouseOut);
orbject.on("mousemove", this.handleMouseMove);
this.orbs[colIdx].push(orbject);
}
}
This has had the benefit of making drag and drop much much faster where before, it was going very slow, but I still can't get my objects to swap position.
To be clear, my main issue is knowing which x, y values I should be changing. At the moment in handleMouseMove, I've been trying to change:
e.target.attrs.x = newX;
e.target.attrs.y = newY;
// newX and newY can be any number
However, no matter what I change it to, it has no effect. So it would help me to know if I'm changing the wrong thing/place, for example, maybe I'm supposed to be changing the Kinetic Circle from the array I've stored? Thanks again.
EDIT 2:
I think I got it! However, I had to take this.orbs and set it in the window at window.orbs, and to test it I did:
window.orbs[0][0].x(450);
window.orbs[0][0].draw();
And this caused the x position to change. But putting it in a window does not seem like good practice?
EDIT 3:
I got the orbs to now swap continuously, except for when it's the same orb being swapped again while mouseover is continuing to fire. At mouseup however, it can be swapped again. I also had to set up multiple layers again to get the mouseover events to work while holding another orb, but the performance seems to have improved a little.
I'm going to try and figure out how to get them to be able to swap continuously on the same mouse hold, but in the meantime, here is the code I wrote to achieve this:
addRow (colIdx) {
for (let rowIdx = 0; rowIdx < 6; rowIdx++) {
// same code as before, changed attr given to Kinetic.Circle
let orbject = new Kinetic.Circle({
x: (rowIdx + 0.5) * 100, y: (colIdx + 0.5) * 100,
width: 100, height: 100,
fill: orbColor, draggable: true, orbId: `orb${colIdx}${rowIdx}`
});
}
}
handleMouseDown (e) {
window.currentOrb = window.orbs[e.target.attrs.orbId];
window.newX = e.target.attrs.x;
window.newY = e.target.attrs.y;
}
Mouse down saving currentOrb by ID and its X and Y
handleMouseUp (e) {
window.currentOrb.x(window.newX);
window.currentOrb.y(window.newY);
window.currentOrb.parent.clear();
window.currentOrb.parent.draw();
window.currentOrb.draw();
window.currentOrb = undefined;
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 6; j++) {
window.orbs[`orb${i}${j}`].draw();
}
}
}
When mouse is released, currently, all orbs are redrawn so they can all be used. I plan to refactor this so only orbs hovered over have this change.
handleMouseMove (e) {
if (window.currentOrb !== undefined && (window.currentOrb.attrs.orbId !== e.target.attrs.orbId)) {
window.orbMove.pause();
window.currentTime = 0;
window.orbMove.play();
let targOrbX = e.target.attrs.x;
let targOrbY = e.target.attrs.y;
// This is the target orb that's being changed's value
// We're storing this in targOrb
e.target.x(window.newX);
e.target.y(window.newY);
e.target.parent.clear();
e.target.parent.draw();
e.target.draw();
// Here we have the previously set current orb's position becoming
// the target orb's position
window.newX = targOrbX;
window.newY = targOrbY;
// Now that the move is made, we can set the newX and Y to be the
// target orb's position once mouseup
}
}
Orb swapping logic which works for passing over orbs once, but not if they are passed over again in the same turn.
When does the "hover" officially take place?
When the mouse event's position enters the second orb? If yes, hit test the mouse vs every non-dragging orb:
// pseudo-code -- make this test for every non-dragging orb
var dx=mouseX-orb[n].x;
var dy=mouseY-orb[n].y;
if(dx*dx+dy*dy<orb[n].radius){
// change orb[n]'s x,y to the dragging orb's x,y (and optionally re-render)
}
When the dragging orb intersects the second orb? If yes, collision test the dragging orb vs every non-dragging orb:
// pseudo-code -- make this test for every non-dragging orb
var dx=orb[draggingIndex].x-orb[n].x;
var dy=orb[draggingIndex].y-orb[n].y;
var rSum=orb[draggingIndex].radius+orb[n].radius;
if(dx*dx+dy*dy<=rSum*rSum){
// change orb[n]'s x,y to the dragging orb's x,y (and optionally re-render)
}
BTW, if you drag an orb over all other orbs, the other orbs will all stack on the dragging orbs original position -- is that what you want?

threeJS, Need some advice to pick an item from a pointcloud with raycasting

I would like to be able to select a point from my pointCloud. To do that, I found a lot of examples:
Interactive particles example
Interactive raycasting pointcloud example
So I wrote the following code:
function intersectionCheck(event)
{
if(pointClouds != null)
{
event.preventDefault();
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersections = raycaster.intersectObjects( pointClouds );
intersection = ( intersections.length ) > 0 ? intersections[ 0 ] : null;
if(intersection != null)
{
console.log(intersection.point);
sphere.position.copy( intersection.point );
}
}
}
That code was supposed to place a green sphere on the screen only if the user clicked on an entity from the pointcloud.
But it was false, the sphere appeard even if there was no entity, as shows the following screenshot:
It seemed that there was a problem with the size of my entities, because the function returned me a position even if I was far away from any entity.
So I changed the way that the position was selected. I checked if the distanceToRay of the point was smaller than sizeOfMyEntities/2.
if(intersection != null)
{
for(var i = 0; i < intersections.length; i++)
{
var testPoint = intersections[i];
if(material.size/2 > testPoint.distanceToRay)
{
point = intersections[i].point;
console.log(point);
sphere.position.copy(point);
break;
}
}
}
Now it works fine, but I'd like to understand why it was not working before. Why is that verification not done in the intersection process?
And also I would like to know if my second function was ok, or if it's a weird way to do what I want.
Is there a better way to do the same?
ps: I am new with all that kind of stuff, so if I am wrong please explain me :D

Html5 canvas how to generate multiple images

Im making a simple zombie game in html5 canvas and wanted to know how to create a zombie every x seconds in a random place? so far i have
var zombies = new Array();
function SummonZombies (){
TotalZombies++;
zombies[TotalZombies] = new Image();
zombies[TotalZombies].src = 'images/monster.png';
ctx.drawImage(zombies[TotalZombies], zombie_x, zombie_y);
}
Only one zombie is being created with this? how would i get it to generate more.
First of all, where are you declaring the variable TotalZombies?
Try something like this :
var zombies = new Array();
for (var i = 0; i < 100; i++) {
var zombie = new Image();
zombie.src = 'images/monster.png';
ctx.drawImage(zombie, Math.floor((Math.random()*100)+1), Math.floor((Math.random()*100)+1));
zombies.push(zombie);
}
This will create 100 zombies, with random x and y positions between 1 and 100. It will add each zombie to the zombies array after they have been instantiated.
You should iterate through zombies array, and invoke drawImage() on everyone.
Extra tip: remember to change x and y after all iteration.
You must separate a Zombi from your zombies :
create a class that will describe what a Zombi is, and only after you will define a collection of such lovely guys and girls :
// This Class defines what a Zombi is.
function Zombi(x,y) {
this.x = x;
this.y = y;
}
var ZombiImage = new Image();
ZombiImage.src = "images/monster.png";
// image of a zombi is shared amongst all zombies, so it is
// defined on the prototype
Zombi.prototype.image = ZombiImage;
// draw the zombi on provided context
Zombi.prototype.draw = function(ctx) {
ctx.drawImage(this.image, this.x, this.y);
}
Now for the collection :
// This class defines a collection of Zombies.
function Zombies() {
this.zombies = [];
}
// summons a zombi at a random place. returns the summoned zombi.
myZombies.prototype.summon() {
var randX = Math.random()*100;
var randY = Math.random()*100;
return this.summonAt(randX, randY);
}
// summons a zombi at x,y. returns the summoned zombi.
myZombies.prototype.summonAt = function (x,y) {
var newZombi = new Zombi(x,y);
this.zombies.push();
return newZombi;
}
// draws all zombies on provided context.
myZombies.prototype.drawAll = function (ctx) {
var i=0;
var __zombies = this.zombies;
for (;i<__zombies.length; i++) {
__zombies[i].draw(ctx);
}
}
// collection of all zombies for your game.
var zombies = new Zombies();
// here you can call zombies.summon(); or zombies.drawAll();
// and even zombies.summonAt(x,y);
In fact the code above is simplified : you must handle the onload event of the image to start the game only after the image was loaded.
But you should get the idea : separate the issues (handle ONE zombi vs a collection of zombies) will get you faster to your goal.
With this -simple- design, you'll be able to easily add-up behaviour to your zombies.
Just one more example in which i will add the seekBrain and walk behaviour :
// This Class defines what a Zombi is.
function Zombi(x,y) {
this.x = x;
this.y = y;
this.dirX = 0 ; // direction X
this.dirY = 0; // direction Y
this.speed = 0.1; // common speed for all zombies
}
// have the zombi seek the brain located at (x,y)
Zombi.prototype.seekBrain = function (x,y) {
this.dirX = (x - this.x );
this.dirY = (y - this.y );
// normalize direction
var norm = Math.sqrt( this.dirX*this.dirX + this.dirY*this.dirY );
this.dirX/=norm;
this.dirY/=norm;
}
// Have the zombi walk in its current direction
Zombi.prototype.walk = function() {
this.x += this.dirX * this.speed;
this.y += this.dirY * this.speed;
}
// image and draw remains the same
And now you might want for your collection :
// makes all zombies walk.
Zombies.walkAll = function() {
var i=0;
var __zombies = this.zombies;
for (;i<__zombies.length; i++) {
__zombies[i].walk();
}
}
// constructor, summon, summonAt, and drawAll remains the same.
So to summon a zombi at random place every xxx ms, do something like :
// summons a zombi at a random place every 2 seconds (==2000 ms)
setTimeInterval(2000, function() { zombies.summon(); } );
now, if hero.x and hero.y are what we guess, you can do :
// Have a random zombi hunt for hero's brain every 2 seconds
setTimeInterval(2000, function() {
var which = Math.floor(zombies.zombies.length * Math.random());
zombies.zombies[which].seekBrain(hero.x, hero.y);
} );
provided you call to zombies.walkAll(); and zombies.drawAll(); on a regular basis, you've got the start of a game ! (i love so much zombies :-) )

three.js serverside collision detection error

Is there a reason why server side usage of three.js 's collision detection should be different from the client side usage? We are using the same scene with the same setup client and server side.
The thing which we are trying todo is determine on the server side if there is collision, with the world. To make this simple we only use 2 boxes for our world. The code used is taken from Lee Stemkoski collision detection example (for which we thank him - it is excellent and clear).
The client side code runs smooth and without trouble, but the serverside code, which is initiated exactly the same way does not detect collisions.
In our demo the player uses his arrows to move. this movement is sent to the server, which has exactly the same scene as the client. Then the transformations are applied (rotations, position changes etc) and then these new position are sent back. The server and client are in sync up to here. However the client detects the hits with our objects in the world (2 boxes) and the server does not.
Clientside:
socket.on("update", function(data){
var delta = clock.getDelta(); // seconds.
var moveDistance = 200 * delta; // 200 pixels per second
var rotateAngle = Math.PI / 2 * delta; // pi/2 radians (90 degrees) per second
if( data.type == "rot" ){
MovingCube.rotation.x = data.x;
MovingCube.rotation.y = data.y;
MovingCube.rotation.z = data.z;
}
if( data.type == "pos" ){
MovingCube.position.x = data.x;
MovingCube.position.y = data.y;
MovingCube.position.z = data.z;
}
var originPoint = MovingCube.position.clone();
for (var vertexIndex = 0; vertexIndex < MovingCube.geometry.vertices.length; vertexIndex++){
var localVertex = MovingCube.geometry.vertices[vertexIndex].clone();
var globalVertex = localVertex.applyMatrix4( MovingCube.matrix );
var directionVector = globalVertex.sub( MovingCube.position );
var ray = new THREE.Raycaster( originPoint, directionVector.clone().normalize() );
var collisionResults = ray.intersectObjects( collidableMeshList );
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )
console.log(" Hit ");
}
})
serverside code
socket.on("update", function(data){
console.log("updating location");
var delta = 0.1 ;//clock.getDelta(); // seconds.
var moveDistance = 200 * delta; // 200 pixels per second
var rotateAngle = Math.PI / 2 * delta; // pi/2 radians (90 degrees) per second
if( data == "A" ){
MovingCube.rotation.y += rotateAngle;
socket.emit("update",{"type":"rot","x":MovingCube.rotation.x,"y":MovingCube.rotation.y,"z":MovingCube.rotation.z});
}
if( data == "D" ){
MovingCube.rotation.y -= rotateAngle;
socket.emit("update",{"type":"rot","x":MovingCube.rotation.x,"y":MovingCube.rotation.y,"z":MovingCube.rotation.z});
}
if ( data == "left" ){
MovingCube.position.x -= moveDistance;
socket.emit("update",{"type":"pos","x":MovingCube.position.x,"y":MovingCube.position.y,"z":MovingCube.position.z});
}
if ( data == "right" ){
MovingCube.position.x += moveDistance;
socket.emit("update",{"type":"pos","x":MovingCube.position.x,"y":MovingCube.position.y,"z":MovingCube.position.z});
}
if ( data == "up" ){
MovingCube.position.z -= moveDistance;
socket.emit("update",{"type":"pos","x":MovingCube.position.x,"y":MovingCube.position.y,"z":MovingCube.position.z});
}
if ( data == "down" ){
MovingCube.position.z += moveDistance;
socket.emit("update",{"type":"pos","x":MovingCube.position.x,"y":MovingCube.position.y,"z":MovingCube.position.z});
}
var originPoint = MovingCube.position.clone();
for (var vertexIndex = 0; vertexIndex < MovingCube.geometry.vertices.length; vertexIndex++){
var localVertex = MovingCube.geometry.vertices[vertexIndex].clone();
var globalVertex = localVertex.applyMatrix4( MovingCube.matrix );
var directionVector = globalVertex.sub( MovingCube.position );
var ray = new THREE.Raycaster( originPoint, directionVector.clone().normalize() );
var collisionResults = ray.intersectObjects( collidableMeshList );
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )
console.log(" Hit ");
}
})
Any help would be great. This has been eating my time for 2 weeks now, there is no error message and i cannot figure out what it is that is going wrong.
Floating point calculations can produce different results on different machines, let me try to find a good article for you.
Here you go, Floating point determinism
Hope it helps
Actually the real problem here is that your server side code probably does not call the render loop from threejs, (which would break of course)
However, the render loop does some additional work for you, it calls the method updateMatrixWorld() on each object -
So serverside, just before doing your raytrace (which uses the world matrix and not the actual position) - just be sure to call
your_objects_you_want_to_raytrace.updateMatrixWorld();
before you do the actual raytrace.
in your case, MovingCube.updateMatrixWorld();

Categories

Resources