Rotation3D

I just though somebody might find this useful! :smiley:

public class Rotation3D {

	public static vec3 point(vec3 center, vec3 point, float xr, float yr, float zr) {
		

		vec3 p = point.copy();
		
		p = Rotation3D.rotateX(center, p, xr);
		p = Rotation3D.rotateY(center, p, yr);
		p = Rotation3D.rotateZ(center, p, zr);
		
		
		return p;
	}

	public static vec3 rotateX(vec3 center, vec3 point, float xr) {
		
		float xrot = (float) Math.toRadians(xr);
		
		float px = point.x;
		float py = point.y;
		float pz = point.z;
		
		float x = px;
		float y = (float) (Math.cos(xrot) * py - Math.sin(xrot) * pz);
		float z = (float) (Math.sin(xrot) * py + Math.cos(xrot) * pz);
		
		return new vec3(x, y, z);
	}
	
	public static vec3 rotateY(vec3 center, vec3 point, float yr) {
		
		float yrot = (float) Math.toRadians(yr);
		
		float px = point.x;
		float py = point.y;
		float pz = point.z;
		
		float x = (float) (Math.cos(yrot) * px + Math.sin(yrot) * pz);
		float y = (float) py;
		float z = (float) (-Math.sin(yrot) * px + Math.cos(yrot) * pz); 
		
		return new vec3(x, y, z);
	}
	
	public static vec3 rotateZ(vec3 center, vec3 point, float zr) {
		
		float zrot = -(float) Math.toRadians(zr);
		
		float px = point.x;
		float py = point.y;
		float pz = point.z;
		
		float x = (float) (Math.cos(zrot) * px - Math.sin(zrot) * py);
		float y = (float) (Math.sin(zrot) * px + Math.cos(zrot) * py);
		float z = pz;
		
		return new vec3(x, y, z);
		
	}
	
}

I have done this using wikipedia on rotation matrices.

PS

vec3 is just a class which stores xyz floats

And then rotate around an arbitrary axis!


public Vector3 rotate(float angle, float x, float y, float z) {
	float cos = (float)Math.cos(angle);
	float sin = (float)Math.sin(angle);
	float oneMinusCos = 1 - cos;
	
	float len = (float)Math.sqrt(x * x + y * y + z * z);
	x /= len;
	y /= len;
	z /= len;
	
	float mat00 = x * x * oneMinusCos + cos;
	float mat10 = x * y * oneMinusCos - z * sin;
	float mat20 = x * z * oneMinusCos + y * sin;
	
	float mat01 = y * x * oneMinusCos + z * sin;
	float mat11 = y * y * oneMinusCos + cos;
	float mat21 = y * z * oneMinusCos - x * sin;
	
	float mat02 = z * x * oneMinusCos - y * sin;
	float mat12 = z * y * oneMinusCos + x * sin;
	float mat22 = z * z * oneMinusCos  + cos;
	
	return new Vector3(x * mat00 + y * mat10 + z * mat20,
							 x * mat01 + y * mat11 + z * mat21,
							 x * mat02 + y * mat12 + z * mat22);
}

Oops I forgot to include the center into the calculations :stuck_out_tongue: