Rotate 3D Cube

We're still using prespective divide technique, but this time we're going to rotate 3D Cube.

It's turn out really simple!, let's think about how to find rotation in 2D vector.

In this section, we just using sin and cos technique.

Let's think about this graph: You will know the key poin of vector rotate is the angle. And alought the vetcor position changed, the r not change(the hypotenuse)! That make things become easier!

Let (x,y) are origin vector, and the (x', y') is the new position vector(It was rotate up to). If we draw some line on it, and we have 2 main angle ∠a & ∠(a + B). (represent for Vector from origin position rotate to new postion angle)

Let's find ∠a first, based on sin = opposite / hypotenuse, and cos = adjacent / hypotenuse.

We find that the Vector(x,y) relationship with angle ∠a:

And same as ∠(a + B)

And by using additional formulas and combine with above formulas, we get:

(Sorry for my hand writing again :(

And that is! We get the relationship between New vector , old vector and angle! So:

And that actually the rotate Matrix came from, write in elegan way

But wait…We're 3D cube, how to apply this 2D formula.

Remember? We're using "Orthographic Projection" which is project 3d into 2d! No magic here, so it was the same!

We just need to lock the rotate direction by different axis.

vec3_t vec3_rotate_x(vec3_t v, float angle) {
  vec3_t rotated_vector = {
    .x = v.x,
    .y = v.y * cos(angle) - v.z * sin(angle),
    .z = v.y * sin(angle) + v.z * cos(angle)
  };
  return rotated_vector;
}

vec3_t vec3_rotate_y(vec3_t v, float angle) {
  vec3_t rotated_vector = {
    .x = v.x * cos(angle) - v.z * sin(angle),
    .y = v.y,
    .z = v.x * sin(angle) + v.z * cos(angle)
  };
  return rotated_vector;
}

vec3_t vec3_rotate_z(vec3_t v, float angle) {
  vec3_t rotated_vector = {
    .x = v.x * cos(angle) - v.y * sin(angle),
    .y = v.x * sin(angle) + v.y * cos(angle),
    .z = v.z
  };
  return rotated_vector;
}

Result

Resources: pikuma course

Date: 2023-12-29 Fri 00:00

Author: Terry Fung

Created: 2024-11-10 Sun 14:09

Emacs 29.4 (Org mode 9.6.15)

Validate