Rotation that points from A to B

From Second Life Wiki
Jump to navigation Jump to search

f_rotDir()

--BETLOG Hax UTC+10: 20091108 1939 [SLT: 20091108 0239]

You are at vector A and you want to know what rotation (quaternion) will intercept vector B.
Yes it's trivial, but after asking numerous very mathematically intelligent persons, and having them invariably misunderstand what I meant/wanted I feel the need to post it here.
Almost instant understanding and elegant answer courtesy of Nomad Padar.
Dude, I say this a lot, but you are seriously awesome.

The code below is merely a test/example harness for something I cannot post here and would only confuse the solution anyway. So yes, it may appear a little redundant. If you are one of the few people who is pleased to learn how this works by finding this example please comment.

//==============================================================
vector      gTarget;
rotation    gAngle;
//----------------------------------
rotation f_rotDir(vector localAxisToPointWith, vector target, vector origin)
{   return llRotBetween(localAxisToPointWith*ZERO_ROTATION, target-origin);
}
//----------------------------------
default
{   state_entry()
    {   llSensor("B", "", AGENT|PASSIVE|SCRIPTED, 3.0, PI);
//        llStopLookAt();
    }
    touch_start(integer num)
    {   if(llDetectedKey(0)==llGetOwner())
        {   llSensor("B", "", AGENT|PASSIVE|SCRIPTED, 3.0, PI);
        }
    }
    sensor(integer num)
    {   vector p=llGetPos();
        gTarget=llDetectedPos(0);
//        gAngle=llRotBetween(<1.0, 0.0, 0.0>* <0,0,0,1>, gTarget-p);
        gAngle=f_rotDir(<1.0, 0.0, 0.0>, gTarget, p);
        llRotLookAt(gAngle, 0.1, 0.1);
/*
llSetText(""
    +"\n gAngle: "+(string)gAngle
    +"\n SHOULD equal:"
    +"\n llGetRot : "+(string)llGetRot()
, <1.0, 1.0, 1.0>, 1.0);
*/
    }
    no_sensor()
    {   llOwnerSay("B not found!");
        llSetText("B not found!", <1.0, 0.0, 0.0>, 1.0);
    }
}
//==============================================================