I'm currently developing a 3d renderer in js.
I'd like to render cubes - and that is working pretty well - but what I'd like to do is something like a rotation of each cube.
So I got some vertex of a cube and I want to rotate the x/y/z (pitch, roll, yaw) of every cube around itself.
This is the 3d rotation function:
let rotate3d = (points = [0,0,0], pitch = 0, roll = 0, yaw = 0) => {
let cosa = Math.cos(yaw),
sina = Math.sin(yaw);
let cosb = Math.cos(pitch),
sinb = Math.sin(pitch);
let cosc = Math.cos(roll),
sinc = Math.sin(roll);
let Axx = cosa*cosb,
Axy = cosa*sinb*sinc - sina*cosc,
Axz = cosa*sinb*cosc + sina*sinc;
let Ayx = sina*cosb,
Ayy = sina*sinb*sinc + cosa*cosc,
Ayz = sina*sinb*cosc - cosa*sinc;
let Azx = -sinb,
Azy = cosb*sinc,
Azz = cosb*cosc;
let px = points[0];
let py = points[1];
let pz = points[2];
points[0] = Axx*px + Axy*py + Axz*pz;
points[1] = Ayx*px + Ayy*py + Ayz*pz;
points[2] = Azx*px + Azy*py + Azz*pz;
return points;
}
and this is a snippet from my renderer routine:
for (let vert of cube.vertex) { let x = vert[0] - camera.position[0], y = vert[1] - camera.position[1], z = vert[2] - camera.position[2]; if (cube.rotation) { cube.rotation += Math.PI * 0.02; let p = rotate(vert.slice(0), cube.r, 0, 0) x = p[0] - camera.position[0] y = p[1] - camera.position[1] z = p[2] - camera.position[2] } # ... draw polygons (cube) by converting 3d coordinates to 2d coordinates. }
So : If the cube is spawned at [0, -1, 0] the program rotates this cube around the y-axis (clockwise). But changing the spawn to [1, -1, 0] lets the cube rotate around the same point (origin) but with space 1. I'd like to rotate the cube on it's spawn!
Edit : This is the spawning cube routine:
spawn(p) {
this.position = p;
const vertex = [[-1,-1,-1], [1,-1,-1], [1,1,-1], [-1,1,-1], [-1,-1,1], [1,-1,1], [1,1,1], [-1,1,1]];
this.vertex = []
for (let vert of vertex) {
let position = []
for (let i=0; i<vert.length; i++) position.push(vert[i]/2 + this.position[i])
this.vertex.push(position)
}
}
So my question: How to edit the rotate function to add a origin point where I'd like to rotate the cube around?
The easiest way to specify the point to rotate around is:
In (pseudo)code:
var translationVector = originPoint.minus(rotationPoint);
myObject.translate(translationVector);
myObject.rotate(eulerX, eulerY, eulerZ);
myObject.translate(-translationVector);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.