I have an Avatar at a given Position (v0) and Rotation (r0)
I have an Object at a givent Position (v1)
I looking for the angle to rotate the avatar toward v1. I need the angle I don't want to use lookAt() function
// Get the Avatar Position
let v0 = new THREE.Vector3();
avatar.getWorldPosition(v0)
// Get the Object Position
let v1 = new THREE.Vector3();
obj.getWorldPosition(v0)
// Get the direction v0 to v1
let dir0 = new THREE.Vector3();
dir0.subVectors( v0, v1 ).normalize();
// Get the direction of avatar (where it look at)
let dir2 = new THREE.Vector3();
avatar.getWorldDirection(dir2)
// Get the angle between the 2 direction
let radians = dir0.angleTo(dir2)
It doesn't work !
The this.mesh.lookAt(v1.setY(0)) works and rotate correctly the mesh
But the angle computation didn't work because of avatar.getWorldDirection
BTW, since everything is on the same plane I don't need 3D (only 2D)
BTW, The avatar (Mixamo) seems to face backward
I need that angle to trigger some animation (if angle > 90 then trigger 90, if angle > 180 then turnback animation...)
Your code has a few mistakes. obj.getWorldPosition(v0) is going to overwrite the v0 values retrieved with avatar.getWorldPosition(v0), so when you subtract v0 - v1 you'll get a vector with a magnitude of 0.
Looking at the documentation of Vector3.angleTo(), it says all you need to do is input the positions, without any subtraction necessary:
let posAvatar = new THREE.Vector3();
avatar.getWorldPosition(posAvatar);
let posObj = new THREE.Vector3();
obj.getWorldPosition(posObj);
const angleRadians = posAvatar.angleTo(posObj);
// convert from radians to degrees
const angleDeg = THREE.MathUtils.radToDeg(angleRadians);
Keep in mind, both objects will need to be on the same plane for this 2D angle to be accurate.
Update:
This approach uses the Javascript Math.atan2() method to calculate the absolute y-axis rotation from your avatar's vantage point towards the obj. This also only uses the x,z positions so any height variations are ignored.
let posAvatar = new THREE.Vector3();
avatar.getWorldPosition(posAvatar);
let posObj = new THREE.Vector3();
obj.getWorldPosition(posObj);
const xDist = posObj.x - posAvatar.x;
const zDist = posObj.z - posAvatar.z;
const angle = Math.atan2(zDist, xDist) * 180 / Math.PI;
avatar.rotation.y = angle;
Your avatar might be facing a different axis, so you can just add 90 or 180 degrees to the final angle value.
Related
I am rotating a cube around a particular axis (x or y or z) by dragging my mouse, lets say while dragging I calculate how much angle rotation I have to appy.
Now I have my current cube rotation in quaternion, and also an array of quaternions containing quaternions of 0, 45, 90, 135, 180, 225, 270, 315, and 360 degrees.
When I am rotating my cube I want to find the closest quaternion from the array, lets say I am rotating in anti-clock and my cube is at 30, then the closest will be quaternion of 90 degrees from the array., similarly for 170 I should get 180 deg quaternion from the array.
currently I am maintaining a variable and depending upon the direction (clock or anti-clock) I am rotating the cube I am managing that variable and finding the next required quaternion from the array. But I need a more efficient way if it exists.
currently My code is doing something like this, If anyone have some solution about this, or a new way of doing this, then please help me
function handleDrag() {
let target = new THREE.Vector3();
raycaster.setFromCamera(mouseNDC, camera);
raycaster.ray.intersectPlane(Zplane, target);
let temp = target
target.sub(mesh.position); // final vector after drag
initial.sub(mesh.position); // initial vector
// get rotation direction using cross product
let xx = new THREE.Vector3().copy(target).normalize()
let yy = new THREE.Vector3().copy(prevDir).normalize()
let dir = yy.cross(xx).z
const angleBtwVec = angleInPlane(initial, target, Zplane.normal);
let quaternion = new THREE.Quaternion();
quaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), angleBtwVec);
let effectiveQuatChange = new THREE.Quaternion().copy(initialCubeQuat)
effectiveQuatChange.multiply(quaternion)
// find next quaterion for which we need to compare for snapping
let check = next
if (dir > 0) { // then anti-clock
check = (next + 1) % 8
} else { // else rotation is in clock direction
check = (next - 1 + 8) % 8
}
// apply quaternion change
mesh.quaternion.copy(effectiveQuatChange)
let reqQuatArray = quaternionArrayYR
let angleDiff = toDegrees(mesh.quaternion.angleTo(reqQuatArray[check]))
console.log(angleDiff, check);
if (angleDiff <= 15) { // if mesh angle with next req quaternion is less than 15 degree, then set mesh quaternion to required quaternion
next = check
mesh.quaternion.copy(reqQuatArray[next]);
initialCubeQuat.copy(reqQuatArray[next]);
initial = temp;
}
prevDir = temp
}
I'm planning to use Orbit Control to do a simple 3rd person camera view,
But I cant seem to figure out how to do it.
when I rotate the camera around an object, and press say “W” key to move forward, I want the object “look” to gradually rotate and move to the new direction the camera is facing.
How can I do that?
It's possible to do exactly that by gradually rotating the object to the camera direction.
Made a codepen here which uses a generic replacement to orbit controls for simplicity:
https://codepen.io/cdeep/pen/QWMWyYW
// Get the X-Z plane in which camera is looking to move the player
camera.getWorldDirection(tempCameraVector);
const cameraDirection = tempCameraVector.setY(0).normalize();
// Get the X-Z plane in which player is looking to compare with camera
model.getWorldDirection(tempModelVector);
const playerDirection = tempModelVector.setY(0).normalize();
// Get the angle to x-axis. z component is used to compare if the angle is clockwise or anticlockwise since angleTo returns a positive value
const cameraAngle = cameraDirection.angleTo(xAxis) * (cameraDirection.z > 0 ? 1 : -1);
const playerAngle = playerDirection.angleTo(xAxis) * (playerDirection.z > 0 ? 1 : -1);
// Get the angle to rotate the player to face the camera. Clockwise positive
const angleToRotate = playerAngle - cameraAngle;
// Get the shortest angle from clockwise angle to ensure the player always rotates the shortest angle
let sanitisedAngle = angleToRotate;
if(angleToRotate > Math.PI) {
sanitisedAngle = angleToRotate - 2 * Math.PI
}
if(angleToRotate < -Math.PI) {
sanitisedAngle = angleToRotate + 2 * Math.PI
}
// Rotate the model by a tiny value towards the camera direction
model.rotateY(
Math.max(-0.05, Math.min(sanitisedAngle, 0.05))
);
As far as I understood all rotations set via object.rotation.x / object.rotation.y / object.rotation.z are applied in respect to object's axes regardless of objects position in scene.
But in the code below after I set simple rotation value box.rotation.y = PI/2
all subsequent changes to box.rotation.x seems to be rotating it not on Box X Axis but on Box Z Axis axis
If I will change box.rotation.z it will still rotate on Box Z Axis just in other direction.
So basically the problem is - rotation by Box X Axis and Box Z Axis doing the same rotation but in different direction.
What am I doing wrong here? How do I use rotation properly here e.g. if I want to apply rotation on Box Z Axis after rotation on Box Y Axis.
here I've created sandbox to reproduce the issue
https://stackblitz.com/edit/trhee-js-plane-rotation?file=index.js
You're running into gimbal lock, so you'll need to use Quaternions to achieve the rotations you want. First you need to set each quat from axis angle, then you'll have to multiply them together to get the desired rotation.
const xAxis = new THREE.Vector3(1, 0, 0);
const xRot = -Math.PI;
const xQuaternion = new THREE.Quaternion();
xQuaternion.setFromAxisAngle( xAxis, xRot );
const yAxis = new THREE.Vector3(0, 1, 0);
const yRot = Math.PI / 2;
const yQuaternion = new THREE.Quaternion();
yQuaternion.setFromAxisAngle( yAxis, yRot );
box.quaternion.multiplyQuaternions(xQuaternion, yQuaternion);
You could add a z-quaternion too using the same method as above, just make sure all 3 quats get multiplied at the end.
I'd like to enable a user to rotate a texture on a rectangle while keeping the aspect ratio of the texture image intact. I'm doing the rotation of a 1:1 aspect ratio image on a surface that is rectangular (say width: 2 and length: 1)
Steps to reproduce:
In the below texture rotation example
https://threejs.org/examples/?q=rotation#webgl_materials_texture_rotation
If we change one of the faces of the geometry like below:
https://github.com/mrdoob/three.js/blob/master/examples/webgl_materials_texture_rotation.html#L57
var geometry = new THREE.BoxBufferGeometry( 20, 10, 10 );
Then you can see that as you play around with the rotation control, the image aspect ratio is distorted. (form a square to a weird shape)
At 0 degree:
At some angle between 0 and 90:
I understand that by changing the repeatX and repeatY factor I can control this. It's also easy to see what the values would be at 0 degree, 90 degree rotations.
But I'm struggling to come up with the formula for repeatX and repeatY that works for any texture rotation given length and width of the rectangular face.
Unfortunately when stretching geometry like that, you'll get a distortion in 3D space, not UV space. In this example, one UV.x unit occupies twice as much 3D space as one UV.y unit:
This is giving you those horizontally-skewed diamonds when in between rotations:
Sadly, there's no way to solve this with texture matrix transforms. The horizontal stretching will be applied after the texture transform, in 3D space, so texture.repeat won't help you avoid this. The only way to solve this is by modifying the UVs so the UV.x units take up as much 3D space as UV.y units:
With complex models, you'd do this kind of "equalizing" in a 3D editor, but since the geometry is simple enough, we can do it via code. See the example below. I'm using a width/height ratio variable to use in my UV.y remapping, that way the UV transformations will match up, regardless of how much wider it is.
//////// Boilerplate Three setup
const renderer = new THREE.WebGLRenderer({canvas: document.querySelector("canvas")});
const camera = new THREE.PerspectiveCamera(50, 1, 1, 100);
camera.position.z = 3;
const scene = new THREE.Scene();
/////////////////// CREATE GEOM & MATERIAL
const width = 2;
const height = 1;
const ratio= width / height; // <- magic number that will help with UV remapping
const geometry = new THREE.BoxBufferGeometry(width, height, width);
let uvY;
const uvArray = geometry.getAttribute("uv").array;
// Re-map UVs to avoid distortion
for (let i2 = 0; i2 < uvArray.length; i2 += 2){
uvY = uvArray[i2 + 1]; // Extract Y value,
uvY -= 0.5; // center around 0
uvY /= ratio; // divide by w/h ratio
uvY += 0.5; // remove center around 0
uvArray[i2 + 1] = uvY;
}
geometry.getAttribute("uv").needsUpdate = true;
const uvMap = new THREE.TextureLoader().load("https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/textures/uv_grid_opengl.jpg");
// Now we can apply texture transformations as expected
uvMap.center.set(0.5, 0.5);
uvMap.repeat.set(0.25, 0.5);
uvMap.anisotropy = 16;
const material = new THREE.MeshBasicMaterial({map: uvMap});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("resize", resize);
// Add rotation on mousemove
function onMouseMove(ev) {
uvMap.rotation = (ev.clientX / window.innerWidth) * Math.PI * 2;
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
function animate(time) {
mesh.rotation.y = Math.cos(time/ 3000) * 2;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
resize();
requestAnimationFrame(animate);
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<script src="https://threejs.org/build/three.js"></script>
<canvas></canvas>
First of all, I agree with the solution #Marquizzo provided to your problem. And setting UV explicitly to the geometry should be the easiest way to solve your problem.
But #Marquizzo did not answer why changing the matrix of the texture (set repeatX and repeatY) does not work.
We all know the 2D rotation matrix R
cos -sin
sin cos
UVs are calculated in the shader with a transform matrix T, which is the texture matrix from your question.
T * UV = new UV
To simplify the question, we only consider rotation. And assume we have another additional matrix X for calculating the new UV. Then we have
X * R * UV = new UV
The question now is whether we can find a solution ofX, so that with any rotation, new UV of any points in your question can be calculated correctly. If there is a solution of X, then we can simply use
var X = new Matrix3();
//X.set(x,y,z,...)
texture.matrix.premultiply(X);
Otherwise, we can't find the approach you expected.
Let's create several equations to figure out X.
In the pic below, ABCD is one face of your geometry, and the transparent green is the texture. The UV of point A is (0,1), point B is (0,0), and (1,0), (1,1) for C and D respectively.
The first equation comes from the consideration, without any rotation, the original UV should never be changed (UV for A is always (0,1)). So we should have
X * I * (0, 1) = (0, 1) // I is the identity matrix
From here we can see X should also be an identity matrix.
Then let's see whether the identity matrix X can satisfy the second equation. What's the second equation? Simplify again, let B be the rotation centre(origin) and rotate the texture 90 degrees(counterclockwise). We use -90 to calculate UV though we rotate 90 degrees.
The new UV for point A after rotating the texture 90 degrees should be the current value of E. The value of E is (a/b, 0). Then we have
From this equation we can see X should not be an identity matrix, which means, WE ARE NOT ABLE TO FIND A SOLUTION OF X TO SOLVE YOUR PROBLEM WITH
X * R * UV = new UV
Certainly, you can change the shader of calculating new UVs, but it's even harder than the way #Marquizzo provided.
I'm trying to make a static 3D prism out of point clouds with specific numbers of particles in each. I've got the the corner coordinates of each side of the prism based on the angle of turn, and tried spawning the particles in the area bound by these coordinates. Instead, the resulting point clouds have kept only the bottom left coordinate.
Screenshot: http://i.stack.imgur.com/uQ7Q8.png
I've tried to set the rotation of each cloud object such that their edges meet, but they will rotate only around the world centre. I gather this is something to do with rotation matrices and Euler angles, but, having been trying to work them out for 3 solid days, I've despaired. (I'm a sociologist, not a dev, and haven't touched graphics before this project.)
Please help? How do I set the rotation on each face of the prism? Or maybe there is a more sensible way to get the particles to spawn in the correct area in the first place?
The code:
// draw the particles
var n = 0;
do {
var geom = new THREE.Geometry();
var material = new THREE.PointCloudMaterial({size: 1, vertexColors: true, color: 0xffffff});
for (i = 0; i < group[n]; i++) {
if (geom.vertices.length < group[n]){
var particle = new THREE.Vector3(
Math.random() * screens[n].bottomrightback.x + screens[n].bottomleftfront.x,
Math.random() * screens[n].toprightback.y + screens[n].bottomleftfront.y,
Math.random() * screens[n].bottomrightfront.z + screens[n].bottomleftfront.z);
geom.vertices.push(particle);
geom.colors.push(new THREE.Color(Math.random() * 0x00ffff));
}
}
var system = new THREE.PointCloud(geom, material);
scene.add(system);
**// something something matrix Euler something?**
n++
}
while (n < numGroups);
I've tried to set the rotation of each cloud object such that their
edges meet, but they will rotate only around the world centre.
It is true they only rotate around 0,0,0. The simple solution then is to move the object to the center, rotate it, and then move it back to its original position.
For example (Code not tested so might take a bit of tweaking):
var m = new THREE.Matrix4();
var movetocenter = new THREE.Matrix4();
movetocenter.makeTranslation(-x, -y, -z);
var rotate = new THREE.Matrix4();
rotate.makeRotationFromEuler(); //Build your rotation here
var moveback = new THREE.Matrix4();
moveback .makeTranslation(x, y, z);
m.multiply(movetocenter);
m.multiply(rotate);
m.multiply(moveback);
//Now you can use geometry.applyMatrix(m)