vector math question. Help pls!!

My question is I have two objects. ObjA at posA and ObjB at posB. ObjA has a normal(facing) and want to know how much deg to turn in order to face ObjB.

vectorBtoA = posA - posB
arccos(dotproduct(normalize(ObjA’s facing)), normalize(vectorBtoA)))

what I get is a degree but don’t have a sign to indicate which way to turn. Any suggestion or better approach?
Thank you very much.

Vector ab = objectB.getPosition().minus(objectA.getPosition());

ab.normalize();

Vector normalA = objectA.getDirection();

normalA.normalize();

double theta = Math.arccos(normalA.dot(ab));

// I've got no idea what this operation is called;
// it's kinda like a cross product... but gives a scalar, not a vector

double cross = ab.x * normalA.y - normalA.x * ab.y;

if(cross<0) theta = -theta;

[quote]// I’ve got no idea what this operation is called;
// it’s kinda like a cross product… but gives a scalar, not a vector

double cross = ab.x * normalA.y - normalA.x * ab.y;

if(cross<0) theta = -theta;
[/quote]
Abuse: It’s still the cross product :wink:
You are generating just the z component of the cross product from the x and y. You can tell whether the y is to the right/left of the x by the sign.

Hata: Do you really need the angle & the sign?
If you just wish to orient the object A to face object B, then the best way is to build the orientation matrix directly, otherwise you will be doing a lot of normalising & trig to get the same result.

For this code, I will assume X is the axis for the ‘facing’ vector, and Y is up:

(Pseudocode)



// Build the true x axis:
vectorX = posA-posB;
vectorX.normalize();

// Now build a true z axis:
vectorY.set(0.0f, 1.0f, 0.0f);
vectorZ.cross( vectorX, vectorY );
vectorZ.normalise();

// Now build the true Y axis:
vectorY.cross( vectorZ, vectorX);

The orientation matrix is actually these three vectors packed into the matrix, either as rows (vectorX, VectorY, VectorZ) or as columns depending on your coordinate scheme.

  • Dom

i think Abuse’s answer is quite smart and it certainly solves this 2d problem :smiley:

thank you Crystalsquid also, i think what u r talking about is orthogonal martix, rite? the reason i asked this question is becos i do want to find out the degree and the sign.

Thank you all.

Ah, ok.

You can also do this in one step, as the size of the cross product result is the sin of the angle:


Vector ab = objectB.getPosition().minus(objectA.getPosition()); 
 
ab.normalize(); 
 
Vector normalA = objectA.getDirection(); 
 
normalA.normalize();  
 
double cross = ab.x * normalA.y - normalA.x * ab.y; 

double theta = Math.arcsin(cross);

  • Dom

that is even better. thanks :slight_smile: