How to control yaw and pitch of mesh in Three.JS? - javascript

I've got a mesh whose yaw and pitch I want to be controlled by user input. I naively tried rotating the mesh about the z and y axes, and that seems to control yaw, but up and down is erratic.
function checkKeys(keys) {
if (keys.left) spaceship.rotation.z += .05;
if (keys.right) spaceship.rotation.z -= .05;
if (keys.up) spaceship.rotation.y += .05;
if (keys.down) spaceship.rotation.y -= .05;
}
How can I make left/right control the plane's yaw and up/down control pitch?
http://jsfiddle.net/trevordixon/d9BN9/2/
Update: I simplified FlyControls.js that wagerfield mentioned so it obeys my gamepad and handles rotation only. Here's what I ended up with (https://gist.github.com/trevordixon/5783321):
THREE.FlyControls = function(object) {
this.object = object;
// API
this.movementSpeed = 1.0;
this.rollSpeed = 0.005;
// disable default target object behavior
this.object.useQuaternion = true;
// internals
this.tmpQuaternion = new THREE.Quaternion();
this.moveState = {up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0};
this.moveVector = new THREE.Vector3(0, 0, 0);
this.rotationVector = new THREE.Vector3(0, 0, 0);
this.handleEvent = function(event) {
if (typeof this[event.type] == 'function') {
this[event.type](event);
}
};
this.update = function(delta) {
this.moveState.yawLeft = -gamepad.axes[2];
this.moveState.pitchDown = gamepad.axes[3];
this.moveState.rollLeft = (Math.abs(gamepad.axes[0]) < 0.15 ? 0 : gamepad.axes[0]) ||
gamepad.buttons[15]/2;
this.moveState.rollRight = (Math.abs(gamepad.axes[1]) < 0.15 ? 0 : gamepad.axes[1]) ||
gamepad.buttons[14]/2;
this.updateRotationVector();
var moveMult = delta * this.movementSpeed;
var rotMult = delta * this.rollSpeed;
this.object.translateX(this.moveVector.x * moveMult);
this.object.translateY(this.moveVector.y * moveMult);
this.object.translateZ(this.moveVector.z * moveMult);
this.tmpQuaternion.set(this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1).normalize();
this.object.quaternion.multiply(this.tmpQuaternion);
// expose the rotation vector for convenience
this.object.rotation.setEulerFromQuaternion(this.object.quaternion, this.object.eulerOrder);
};
this.updateRotationVector = function() {
this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
};
function bind(scope, fn) {
return function () {
fn.apply( scope, arguments );
};
};
this.updateRotationVector();
};

The yaw axis is the up axis, or y-axis in this case, so you need to rotate your spaceship geometry so it is level to begin with:
geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
Then you need to change the eulerOrder of you spaceship so yaw (Y) is first and pitch (X) is second:
spaceship.rotation.order = "YXZ"; // three.js r.65
Then you need to adjust your keycodes accordingly.
three.js r.65

The problem you are encountering is due to the way in which rotations are calculated and applied to objects in three.js (well, 3D engines in general). For each rotation axis (x, y & z) a rotation matrix is multiplied onto the object's matrix (which contains it's position, scale and rotation).
Since matrices are non-commutative; meaning that A * B != B * A, the order of multiplication matters. By default this 'Euler order' is X then Y then Z. That is why your Z rotation seems to make sense, but your Y rotation is not what you would intuitively expect it to be.
Have no fear, there is a solution! I assume that you would like your plane to rotate in the same fashion as the camera in this demo where each additional change in rotation is applied relative to the current rotation. In 3D programs like 3D Studio Max, this is known as a local rotation:
http://threejs.org/examples/webgl_geometry_terrain.html
If you inspect the source of this demo, you will see that the controls for the camera are created on line 76:
controls = new THREE.FirstPersonControls( camera );
There are also FlyControls, which may be more suitable for you?
http://threejs.org/examples/misc_controls_fly.html
Either way, I would start by playing around with these ready-made controls and using your plane object in the constructor rather than the camera.
Hope that helps.

Related

THREE.js orthographic camera zoom to mouse point

I'm working on an orthographic camera for our THREE.js app. Essentially, this camera will present the scene to the user in 2D (users have the option of switching between the 2D and 3D camera). This camera will allow for panning and zooming to mouse point. I have the panning working, and I have zooming working, but not zooming to mouse point. Here's my code:
import React from 'react';
import T from 'three';
let panDamper = 0.15;
let OrthoCamera = React.createClass({
getInitialState: function () {
return {
distance: 150,
position: { x: 8 * 12, y: 2 * 12, z: 20 * 12 },
};
},
getThreeCameraObject: function () {
return this.camera;
},
applyPan: function (x, y) { // Apply pan by changing the position of the camera
let newPosition = {
x: this.state.position.x + x * -1 * panDamper,
y: this.state.position.y + y * panDamper,
z: this.state.position.z
};
this.setState({position: newPosition});
},
applyDirectedZoom: function(x, y, z) {
let zoomChange = 10;
if(z < 0) zoomChange *= -1;
let newDistance = this.state.distance + zoomChange;
let mouse3D = {
x: ( x / window.innerWidth ) * 2 - 1,
y: -( y / window.innerHeight ) * 2 + 1
};
let newPositionVector = new T.Vector3(mouse3D.x, mouse3D.y, 0.5);
newPositionVector.unproject(this.camera);
newPositionVector.sub(this.camera.position);
let newPosition = {
x: newPositionVector.x,
y: newPositionVector.y,
z: this.state.position.z
};
this.setState({
distance: newDistance,
position: newPosition
});
},
render: function () {
let position = new T.Vector3(this.state.position.x, this.state.position.y, this.state.position.z);
let left = (this.state.distance / -2) * this.props.aspect + this.state.position.x;
let right = (this.state.distance / 2) * this.props.aspect + this.state.position.x;
let top = (this.state.distance / 2) + this.state.position.y;
let bottom = (this.state.distance / -2) + this.state.position.y;
// Using react-three-renderer
// https://github.com/toxicFork/react-three-renderer
return <orthographicCamera
{...(_.pick(this.props, ['near', 'far', 'name']))}
position={position}
left={left}
right={right}
top={top}
bottom={bottom}
ref={(camera) => this.camera = camera}/>
}
});
module.exports = OrthoCamera;
Some zooming towards the mouse point happens but it seems erratic. I want to keep a 2D view, so as I zoom, I also move the camera (rather than having a non-perpendicular target, which kills the 2D effect).
I took cues from this question. As far as I can tell, I am successfully converting to THREE.js coordinates in mouse3D (see the answer to this question).
So, given this setup, how can I smoothly zoom to the mouse point (mouse3D) using the orthographic camera and maintaining a two dimensional view? Thanks in advance.
Assuming you have a camera that is described by a position and a look-at (or pivot) point in world coordinates, zooming at (or away from) a specific point is quite simple at its core.
Your representation seems to be even simpler: just a position/distance pair. I didn't see a rotation component, so I'll assume your camera is meant to be a top-down orthographic one.
In that case, your look-at point (which you won't need) is simply (position.x, position.y - distance, position.z).
In the general case, all you need to do is move both the camera position and the look-at point towards the zoom-at point while preserving the camera normal (i.e. direction). Note that this will work regardless of projection type or camera rotation. EDIT (2020/05/01): When using an orthographic projection, this is not all you need to do (see update at the bottom).
If you think about it, this is exactly what happens when you're zooming at a point in 3D. You keep looking at the same direction, but you move ever closer (without ever reaching) your target.
If you want to zoom by a factor of 1.1 for example, you can imagine scaling the vector connecting your camera position to your zoom-at point by 1/1.1.
You can do that by simply interpolating:
var newPosition = new THREE.Vector3();
newPosition.x = (orgPosition.x - zoomAt.x) / zoomFactor + zoomAt.x;
newPosition.y = (orgPosition.y - zoomAt.y) / zoomFactor + zoomAt.y;
newPosition.z = (orgPosition.z - zoomAt.z) / zoomFactor + zoomAt.z;
As I said above, in your case you won't really need to update a look-at point and then calculate the new distance. Your new distance will simply be:
var newDistance = newPosition.y
That should do it.
It only gets a little bit more sophisticated (mainly in the general case) if you want to set minimum and maximum distance limits both between the position/look-at and position/zoom-at point pairs.
UPDATE (2020/05/01):
I just realized that the above, although correct (except for missing one minor but very important step) is not a complete answer to OP's question. Changing the camera's position in orthographic mode won't of course change the scale of graphics being rendered. For that, the camera's projection matrix will have to be updated (i.e. the left, right, top and bottom parameters of the orthographic projection will have to be changed).
For this reason, many graphics libraries include a scaling factor in their orthographic camera class, which does exactly that. I don't have experience with ThreeJS, but I think that property is called 'zoom'.
So, summing everything up:
var newPosition = new THREE.Vector3();
newPosition.x = (orgPosition.x - zoomAt.x) / zoomFactor + zoomAt.x;
newPosition.y = (orgPosition.y - zoomAt.y) / zoomFactor + zoomAt.y;
newPosition.z = (orgPosition.z - zoomAt.z) / zoomFactor + zoomAt.z;
myCamera.zoom = myCamera.zoom * zoomFactor
myCamera.updateProjectionMatrix()
If you want to use your orthographic camera class code above instead, you will probably have to change the section that computes left, right, top and bottom and add a scaling factor in the calculation. Here's an example:
var aspect = this.viewportWidth / this.viewportHeight
var dX = (this.right - this.left)
var dY = (this.top - this.bottom) / aspect
var left = -dX / (2 * this.scale)
var right = dX / (2 * this.scale)
var bottom = -dY / (2 * this.scale)
var top = dY / (2 * this.scale)
mat4.ortho(this.mProjection, left, right, bottom, top, this.near, this.far)

Click to place camera near an object in Three js

My I am trying to do a click to zoom feature with Three.js, I have a canvas and an object loaded in the canvas.On click I am trying to place the camera near the point of intersection(Actually like zooming that point).
Here is what I have done, but doesn't work as I wanted, on click camera positions changes but kind of works partially sometimes camera is placed near the point of intersection, some times not.
onmousedown = function (event) {
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
event.preventDefault();
mouse.x = (event.clientX / self.renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / self.renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, self.camera);
var objects = [];
for (var i = 0; i < self.scene.children.length; i++) {
if (self.scene.children[i] instanceof THREE.Group) {
objects.push(self.scene.children[i]);
}
}
console.log(objects);
var intersects = raycaster.intersectObjects( objects,true );
console.log(intersects.length);
if (intersects.length > 0) {
self.camera.up = new THREE.Vector3(0, 0, 1);
self.camera.lookAt(new THREE.Vector3(0, 0, 0));
self.camera.position.z = intersects[0].point.z * .9;
self.camera.position.x = intersects[0].point.x * .9;
self.camera.position.y = intersects[0].point.y * .9;
}
};
Here self is a global viewer object which holds camera, canvas, different objects etc.
0.9 is just a number used to place camera just near the point of intersection.
camera used is PerspectiveCamera and controls is TrackballControls
new THREE.PerspectiveCamera(90, this.width / this.height, 1, 1000);
The objects loaded are from .obj or .dae files ,I expect this to work like click on any point on the object and place the camera near that point. But camera is moving but sometimes not near the point I clicked.
Does intersects[0] gives the nearest intersection point? or nearest in the direction of camera ?
What is my mistake here ?
I am new to three js , just started learning it.If something or some logic is wrong help me with that.
The position is a bit complicated to calculate; you have to find the segment between camera and intersection and than place the camera at specific distance from intersection along the segment looking to the intersection point.
try this:
var length=[the desiderated distance camera-intersection]
var dir = camera.position.clone().sub(intersects[0].point).normalize().multiplyScalar(length);
camera.position = intersects[0].point.clone().add(dir);
camera.lookAt(intersects[0].point);
I have created a fiddle: http://jsfiddle.net/h5my29aL/
It's not so difficult. Think of your object as a planet, and your camera as a satellite. You need to position the camera somewhere in an orbit near your object. Three contains a distanceTo function that makes it simple. The example uses a sphere, but it will work with an arbitrary mesh. It measures the distance from the center point to the desired vector3. In your case the vector3 is likely the face position returned by a picker ray. But anyhow, the lookAt is set to the mesh, and then a distance from the vertex is calculated so that the camera is always the same altitude regardless of a vertex's or face's distance from the object center.
var point = THREE.GeometryUtils.randomPointsInGeometry( geometry, 1 );
var altitude = 100;
var rad = mesh.position.distanceTo( point[0] );
var coeff = 1+ altitude/rad;
camera.position.x = point[0].x * coeff;
camera.position.y = point[0].y * coeff;
camera.position.z = point[0].z * coeff;
camera.lookAt(mesh.position);
I've came somewhat close to what I want with an example from Three js.
Three JS webgl_decals
this is what I have done.
function zoomCam(event) {
var point_mouse = new THREE.Vector2(),
var point_x = null;
var point_y = null;
if (event.changedTouches) {
point_x = event.changedTouches[ 0 ].pageX;
point_y = event.changedTouches[ 0 ].pageY;
} else {
point_x = event.clientX;
point_y = event.clientY;
}
point_mouse.x = (point_x / window.innerWidth) * 2 - 1;
point_mouse.y = -(point_y / window.innerHeight) * 2 + 1;
if (sceneObjects.length > 0) {
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera(point_mouse, camera);
var intersects = raycaster.intersectObjects(sceneObjects, true);
if (intersects.length > 0) {
var p = intersects[ 0 ].point;
var n = intersects[ 0 ].face.normal.clone();
n.multiplyScalar(10);
n.add(intersects[ 0 ].point);
camera.position.copy(n);
camera.lookAt(p);
}
}
There might be some minor issues as I formatted/changed the code for answering here. Check the code before implementing.

Three.js 2D X, Y coords to 3D X, Y, Z coords always in front of camera

I've looked at this question:
Mouse / Canvas X, Y to Three.js World X, Y, Z
and have implemented it in my code, the problem is that I can't seem to get it to work as others have stated.
I need to place an object in front of the camera via X and Y screen coords, not necessarily from the mouse.
This object will be at a specified distance in front of the camera, either from a pre-defined maximum distance or a calculated object distance.
Note: My Camera can be at any position in my scene and facing any direction
Here is my code:
this.reticlePos.x = 500;
this.reticlePos.y = 300;
this.reticlePos.z = 0.5;
this.projector.unprojectVector(this.reticlePos, this.camera);
//check for collisions, if collisions set distance to collision distance
var distance = this.RETICLE_RADIUS;
var direction = new THREE.Vector3( 0, 0, -1 );
direction.applyQuaternion( this.camera.quaternion );
this.rayCaster.set(this.camera.position, direction);
var collisionResults = this.rayCaster.intersectObjects(this.sceneController.obstacles);
if( collisionResults.length !== 0 ) {
// console.log('Ray collides with mesh. Distance :' + collisionResults[0].distance);
distance = collisionResults[0].distance - 20;
}
// set the reticle position
var dir = this.reticlePos.clone().sub( this.camera.position ).normalize();
var pos = this.camera.position.clone().add( dir.multiplyScalar( distance ) );
this.reticleMesh.position.copy( pos );
As you can see is is very similar to the linked question, yet I cannot see the object in front of my camera.
Any insight into this would be greatly appreciated.
I figured out the answer myself for anyone that checks this question later on.
To get my screen coordinates I needed to convert some input data from a gyroscope, and didn't realize that I still needed to do the following to my calculated screen coordinates:
this.reticlePos.x = ( this.reticlePos.x / window.innerWidth ) * 2 - 1;
this.reticlePos.y = - ( this.reticlePos.y / window.innerHeight ) * 2 + 1;
After doing this, everything works as expected.

How to detect collision in three.js?

I am using three.js.
I have two mesh geometries in my scene.
If these geometries are intersected (or would intersect if translated) I want to detect this as a collision.
How do I go about performing collision detection with three.js? If three.js does not have collision detection facilities, are there other libraries I might use in conjuction with three.js?
In Three.js, the utilities CollisionUtils.js and Collisions.js no longer seem to be supported, and mrdoob (creator of three.js) himself recommends updating to the most recent version of three.js and use the Ray class for this purpose instead. What follows is one way to go about it.
The idea is this: let's say that we want to check if a given mesh, called "Player", intersects any meshes contained in an array called "collidableMeshList". What we can do is create a set of rays which start at the coordinates of the Player mesh (Player.position), and extend towards each vertex in the geometry of the Player mesh. Each Ray has a method called "intersectObjects" which returns an array of objects that the Ray intersected with, and the distance to each of these objects (as measured from the origin of the Ray). If the distance to an intersection is less than the distance between the Player's position and the geometry's vertex, then the collision occurred on the interior of the player's mesh -- what we would probably call an "actual" collision.
I have posted a working example at:
http://stemkoski.github.io/Three.js/Collision-Detection.html
You can move the red wireframe cube with the arrow keys and rotate it with W/A/S/D. When it intersects one of the blue cubes, the word "Hit" will appear at the top of the screen once for every intersection as described above. The important part of the code is below.
for (var vertexIndex = 0; vertexIndex < Player.geometry.vertices.length; vertexIndex++)
{
var localVertex = Player.geometry.vertices[vertexIndex].clone();
var globalVertex = Player.matrix.multiplyVector3(localVertex);
var directionVector = globalVertex.subSelf( Player.position );
var ray = new THREE.Ray( Player.position, directionVector.clone().normalize() );
var collisionResults = ray.intersectObjects( collidableMeshList );
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )
{
// a collision occurred... do something...
}
}
There are two potential problems with this particular approach.
(1) When the origin of the ray is within a mesh M, no collision results between the ray and M will be returned.
(2) It is possible for an object that is small (in relation to the Player mesh) to "slip" between the various rays and thus no collision will be registered. Two possible approaches to reduce the chances of this problem are to write code so that the small objects create the rays and do the collision detection effort from their perspective, or include more vertices on the mesh (e.g. using CubeGeometry(100, 100, 100, 20, 20, 20) rather than CubeGeometry(100, 100, 100, 1, 1, 1).) The latter approach will probably cause a performance hit, so I recommend using it sparingly.
I hope that others will contribute to this question with their solutions to this question. I struggled with it for quite a while myself before developing the solution described here.
An updated version of Lee's answer that works with latest version of three.js
for (var vertexIndex = 0; vertexIndex < Player.geometry.attributes.position.array.length; vertexIndex++)
{
var localVertex = new THREE.Vector3().fromBufferAttribute(Player.geometry.attributes.position, vertexIndex).clone();
var globalVertex = localVertex.applyMatrix4(Player.matrix);
var directionVector = globalVertex.sub( Player.position );
var ray = new THREE.Raycaster( Player.position, directionVector.clone().normalize() );
var collisionResults = ray.intersectObjects( collidableMeshList );
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )
{
// a collision occurred... do something...
}
}
This really is far too broad of a topic to cover in a SO question, but for the sake of greasing the SEO of the site a bit, here's a couple of simple starting points:
If you want really simple collision detection and not a full-on physics engine then check out (link removed due to no more existing website)
If, on the other hand you DO want some collision response, not just "did A and B bump?", take a look at (link removed due to no more existing website), which is a super easy to use Ammo.js wrapper built around Three.js
only works on BoxGeometry and BoxBufferGeometry
create the following function:
function checkTouching(a, d) {
let b1 = a.position.y - a.geometry.parameters.height / 2;
let t1 = a.position.y + a.geometry.parameters.height / 2;
let r1 = a.position.x + a.geometry.parameters.width / 2;
let l1 = a.position.x - a.geometry.parameters.width / 2;
let f1 = a.position.z - a.geometry.parameters.depth / 2;
let B1 = a.position.z + a.geometry.parameters.depth / 2;
let b2 = d.position.y - d.geometry.parameters.height / 2;
let t2 = d.position.y + d.geometry.parameters.height / 2;
let r2 = d.position.x + d.geometry.parameters.width / 2;
let l2 = d.position.x - d.geometry.parameters.width / 2;
let f2 = d.position.z - d.geometry.parameters.depth / 2;
let B2 = d.position.z + d.geometry.parameters.depth / 2;
if (t1 < b2 || r1 < l2 || b1 > t2 || l1 > r2 || f1 > B2 || B1 < f2) {
return false;
}
return true;
}
use it in conditional statements like this:
if (checkTouching(cube1,cube2)) {
alert("collision!")
}
I have an example using this at https://3d-collion-test.glitch.me/
Note: if you rotate(or scale) one (or both) of the cubes/prisims, it will detect as though they haven't been turned(or scaled)
since my other answer is limited I made something else that is more accurate and only returns true when there is a collision and false when there isn't (but sometimes when There still is)
anyway, First make The Following Function:
function rt(a,b) {
let d = [b];
let e = a.position.clone();
let f = a.geometry.vertices.length;
let g = a.position;
let h = a.matrix;
let i = a.geometry.vertices;
for (var vertexIndex = f-1; vertexIndex >= 0; vertexIndex--) {
let localVertex = i[vertexIndex].clone();
let globalVertex = localVertex.applyMatrix4(h);
let directionVector = globalVertex.sub(g);
let ray = new THREE.Raycaster(e,directionVector.clone().normalize());
let collisionResults = ray.intersectObjects(d);
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() ) {
return true;
}
}
return false;
}
that above Function is the same as an answer in this question by
Lee Stemkoski (who I am giving credit for by typing that) but I made changes so it runs faster and you don't need to create an array of meshes. Ok step 2: create this function:
function ft(a,b) {
return rt(a,b)||rt(b,a)||(a.position.z==b.position.z&&a.position.x==b.position.x&&a.position.y==b.position.y)
}
it returns true if the center of mesh A isn't in mesh B AND the center of mesh B isn't in A OR There positions are equal AND they are actually touching. This DOES still work if you scale one (or both) of the meshes.
I have an example at: https://3d-collsion-test-r.glitch.me/
It seems like this has already been solved but I have an easier solution if you are not to comfortable using ray casting and creating your own physics environment.
CANNON.js and AMMO.js are both physics libraries built on top of THREE.js. They create a secondary physics environment and you tie your object positions to that scene to emulate a physics environment. the documentation is simple enough to follow for CANNON and it is what I use but it hasnt been updated since it was released 4 years ago. The repo has since been forked and a community keeps it updated as cannon-es. I will leave a code snippet here so you can see how it works
/**
* Floor
*/
const floorShape = new CANNON.Plane()
const floorBody = new CANNON.Body()
floorBody.mass = 0
floorBody.addShape(floorShape)
floorBody.quaternion.setFromAxisAngle(
new CANNON.Vec3(-1,0,0),
Math.PI / 2
)
world.addBody(floorBody)
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(10, 10),
new THREE.MeshStandardMaterial({
color: '#777777',
metalness: 0.3,
roughness: 0.4,
envMap: environmentMapTexture
})
)
floor.receiveShadow = true
floor.rotation.x = - Math.PI * 0.5
scene.add(floor)
// THREE mesh
const mesh = new THREE.Mesh(
sphereGeometry,
sphereMaterial
)
mesh.scale.set(1,1,1)
mesh.castShadow = true
mesh.position.copy({x: 0, y: 3, z: 0})
scene.add(mesh)
// Cannon
const shape = new CANNON.Sphere(1)
const body = new CANNON.Body({
mass: 1,
shape,
material: concretePlasticMaterial
})
body.position.copy({x: 0, y: 3, z: 0})
world.addBody(body)
This makes a floor and a ball but also creates the same thing in the CANNON.js enironment.
const tick = () =>
{
const elapsedTime = clock.getElapsedTime()
const deltaTime = elapsedTime - oldElapsedTime
oldElapsedTime = elapsedTime
// Update Physics World
mesh.position.copy(body.position)
world.step(1/60,deltaTime,3)
// Render
renderer.render(scene, camera)
// Call tick again on the next frame
window.requestAnimationFrame(tick)
}
After this you just update the position of your THREE.js scene in the animate function based on the position of your physics scene.
Please check out the documentation as it might seem more complicated than it really is. Using a physics library is going to be the easiest way to simulate collisions. Also check out Physi.js, I have never used it but it is supposed to be a more friendly library that doesn't require you to make a secondary environment
In my threejs version, I only have geometry.attributes.position.array and not geometry.vertices. To convert it to vertices, I use the following TS function:
export const getVerticesForObject = (obj: THREE.Mesh): THREE.Vector3[] => {
const bufferVertices = obj.geometry.attributes.position.array;
const vertices: THREE.Vector3[] = [];
for (let i = 0; i < bufferVertices.length; i += 3) {
vertices.push(
new THREE.Vector3(
bufferVertices[i] + obj.position.x,
bufferVertices[i + 1] + obj.position.y,
bufferVertices[i + 2] + obj.position.z
)
);
}
return vertices;
};
I pass in the object's position for each dimension because the bufferVertices by default are relative to the object's center, and for my purposes I wanted them to be global.
I also wrote up a little function to detect collisions based on vertices. It optionally samples vertices for very involved objects, or checks for proximity of all vertices to the vertices of the other object:
const COLLISION_DISTANCE = 0.025;
const SAMPLE_SIZE = 50;
export const detectCollision = ({
collider,
collidables,
method,
}: DetectCollisionParams): GameObject | undefined => {
const { geometry, position } = collider.obj;
if (!geometry.boundingSphere) return;
const colliderCenter = new THREE.Vector3(position.x, position.y, position.z);
const colliderSampleVertices =
method === "sample"
? _.sampleSize(getVerticesForObject(collider.obj), SAMPLE_SIZE)
: getVerticesForObject(collider.obj);
for (const collidable of collidables) {
// First, detect if it's within the bounding box
const { geometry: colGeometry, position: colPosition } = collidable.obj;
if (!colGeometry.boundingSphere) continue;
const colCenter = new THREE.Vector3(
colPosition.x,
colPosition.y,
colPosition.z
);
const bothRadiuses =
geometry.boundingSphere.radius + colGeometry.boundingSphere.radius;
const distance = colliderCenter.distanceTo(colCenter);
if (distance > bothRadiuses) continue;
// Then, detect if there are overlapping vectors
const colSampleVertices =
method === "sample"
? _.sampleSize(getVerticesForObject(collidable.obj), SAMPLE_SIZE)
: getVerticesForObject(collidable.obj);
for (const v1 of colliderSampleVertices) {
for (const v2 of colSampleVertices) {
if (v1.distanceTo(v2) < COLLISION_DISTANCE) {
return collidable;
}
}
}
}
};
You could try cannon.js.It makes it easy to do collision and its my favorite collision detection library. There is also ammo.js too.

What is the algorithm for storing the pixels in a spiral in JS?

What is the algorithm for storing the pixels in a spiral in JS?
http://www.mathematische-basteleien.de/spiral.htm
var Spiral = function(a) {
this.initialize(a);
}
Spiral.prototype = {
_a: 0.5,
constructor: Spiral,
initialize: function( a ) {
if (a != null) this._a = a;
},
/* specify the increment in radians */
points: function( rotations, increment ) {
var maxAngle = Math.PI * 2 * rotations;
var points = new Array();
for (var angle = 0; angle <= maxAngle; angle = angle + increment)
{
points.push( this._point( angle ) );
}
return points;
},
_point: function( t ) {
var x = this._a * t * Math.cos(t);
var y = this._a * t * Math.sin(t);
return { X: x, Y: y };
}
}
var spiral = new Spiral(0.3);
var points = spiral.points( 2, 0.01 );
plot(points);
Sample implementation at http://myweb.uiowa.edu/timv/spiral.htm
There are a couple of problems with this question. The first is that you're not really being specific about what you're doing.
1) Javascript isn't really a storage medium, unless you're looking to transmit the pixels using JSON, in which case you may want to rephrase to explicitly state that.
2) There's no mention of what you expect the spiral to look like - are we talking about a loose spiral or a tight spiral? Monocolor or a gradient or a series of colors ? Are you looking at a curved spiral or a rectangular one?
3) What is the final aim here? Are you looking to draw the spiral directly using JS or are you transmitting it to some other place?

Categories