Vector3 rotations without Matrix4

Any community contributions to libgdx go here! Some may get included in the core API when permission is granted.

Vector3 rotations without Matrix4

Postby tenfour04 » Thu Sep 15, 2011 3:22 am

I'm not sure if this is somewhere in the code, and I just haven't found it, but it would be nice to be able to rotate Vectors without having to use/create a Matrix. I checked LibGDX 0.9.1--haven't checked later versions to see if this has already been added.

I have been using this code in my own version of Vector3. There are methods to rotate about each of the main axes, and then one to rotate about an arbitrary axis.

In the last method, the rotation axis must be normalized to keep the equations as simple as they are. I left that out of the method, so there wouldn't be cases where there was time wasted normalizing a unit vector. But maybe that would be rare--depends on how people would want to use this.

Code: Select all
private float sin,cos,x0,y0,z0,com;

   public Vector3 rotateX(float angRad){
      sin = MathUtils.sin(angRad);
      cos = MathUtils.cos(angRad);
      return set(x,y*cos - z*sin,z*cos + y*sin);
   }
   
   public Vector3 rotateY(float angRad){
      sin = MathUtils.sin(angRad);
      cos = MathUtils.cos(angRad);
      return set(z*sin + x*cos,y,z*cos - x*sin);
   }
   
   public Vector3 rotateZ(float angRad){
      sin = MathUtils.sin(angRad);
      cos = MathUtils.cos(angRad);
      return set(x*cos - y*sin,x*sin + y*cos,z);
   }

   /**@param rot Axis of rotation. Must be normalized!*/   
   public Vector3 rotate(Vector3 rot, float angRad){
      sin = FastTrig.sin(angRad);
      cos = FastTrig.cos(angRad);
      com = (rot.x*x+rot.y*y+rot.z*z)*(1-cos);
      x0=rot.x*com+x*cos+(-rot.z*y+rot.y*z)*sin;
      y0=rot.y*com+y*cos+(rot.z*x-rot.x*z)*sin;
      z0=rot.z*com+z*cos+(-rot.y*x+rot.x*y)*sin;
      return set(x0,y0,z0);
   }


Edit: I realized I might be breaking the rules! This code is just an example for discussion. I'd be happy to add Javadocs if desired. Apache License is fine, but it's so short and probably been done a thousand times before, that I'm not sure that matters..
tenfour04
 
Posts: 1235
Joined: Sat Jun 18, 2011 3:24 pm

Return to Libgdx Contributions

Who is online

Users browsing this forum: No registered users and 1 guest