I've been creating a 3D engine over the past few weeks, and I've managed to get translation and scaling for my objects. But I'm having a slight issue with my rotations. When I try rotating my cube 45 degrees on the z-axis, it becomes warped.
Here is where all my calculations for the cubes rotation are. 'vertices' is an array containing all points in my cube. The code is limited to just rotating along the z-axis.
public void rotate(vec3 r) {
rotation.add(r);
float sinZ = (float) Math.sin(Math.toRadians(r.z));
float cosZ = (float) Math.cos(Math.toRadians(r.z));
for (int vdx = 0; vdx < vertices.size(); vdx++) {
vec3 v = vertices.get(vdx);
v.x = v.x * cosZ - v.y * sinZ;
v.y = v.y * cosZ + v.x * sinZ;
vertices.set(vdx, v);
}
}
Assume the cube is at the location (0, 0, 0)
I would preferably like to do this without using external modules.
You need temporary variables x, y like:
x = v.x * cosZ - v.y * sinZ;
y = v.y * cosZ + v.x * sinZ;
v.x = x;
v.y = y;
Otherwise the computation of v.y is using the wrong v.x