# Quaternions from two vectors

Hi,

I need to position a cylinder to the direction of two vectors,

I’ve created the cylinder and positioned it in the mid point between two vectors, but couldn’t rotate it to the correct direction…

I’ve tried to create a Quaternion from the angle and axis but it doesn’t seem to work…

[java]

Vector3f prevVec = new Vector3f(prevPoint.getX(), prevPoint.getZ(), prevPoint.getY());

Vector3f thsVec = new Vector3f(ths_point.getX(), ths_point.getZ(), ths_point.getY());

float cyl_height = prevVec.distance(thsVec);

Vector3f cyl_midpt = prevVec.interpolate(thsVec, 0.5f);

Vector3f diff_vec = thsVec.subtract(prevVec).normalize();

Vector3f rot_axis = diff_vec.cross(new Vector3f(0, 0, 1));

float rot_angle = rot_axis.angleBetween(new Vector3f(0, 0, 1));

Quaternion q = new Quaternion();

q.fromAngleAxis(rot_angle, rot_axis.normalize());

Cylinder cyl = new Cylinder(5, 5, 0.3f, cyl_height, true);

Geometry geom = new Geometry(“Cylinder”, cyl);

geom.updateModelBound();

mat.setColor(“m_Color”, ColorRGBA.Red);

geom.setMaterial(mat);

geom.setLocalRotation(q);

geom.setLocalTranslation(cyl_midpt);

[/java]

Isn’t the axis just prevVec X thsVec? And the angle would then be prevVec.angleBetween(thsVec)?

Thanks… but it doesn’t seem to work that way either…

I have to position the cylinder in between the vectors ‘prevVec’ and 'thsVec '.

The axis seems to be the ‘prevVec X thsVec’ but how can I find the angle…?

I really need to figure this out… :roll:

Uh… if thats all you need:

Uh, nvm… Why do you need the angle? can you maybe solve it with lookAt()?

1 Like

Thanks…

but it only gives the vector that is in the wanted direction…

can you please explain how can i position a cylinder which now resides in (0,0,0) to that position…

(The cylinder’s top face has to be in the prevVec and the bottom face have to be in the thsVec),

Try this:

[java]

Vector3f middlePos = prevVec.interpolate(thsVec, 0.5f);

cylinderGeometry.setLocalTranslation(middlePos);

cylinderGeometry.lookAt(prevVec,Vector3f.Z);[/java]

It worked…!!!

Thanks Normem & Momoko_Fan for the support… I really appreciate it very much… you guys are the best!!!

This is what i’ve done…

[java]

Vector3f cyl_midpt = prevVec.interpolate(thsVec, 0.5f);

Vector3f diff_vec = thsVec.subtract(prevVec);

// after creating the cylinder and the geometry…

geom.lookAt(diff_vec, new Vector3f(0, 1, 0));

geom.setLocalTranslation(cyl_midpt);

[/java]

Thanks…