Author Topic: Spawn an object facing a point  (Read 1608 times)

I'm trying to create an object which is rotated towards a specific point. I have a 3D vector of the positional difference, but TGE uses axis angles for rotation. I've tried the following three methods of conversion, but none of them work properly. Any ideas?

Code: [Select]
function vectorToAxis( %vector )
{
%normal = vectorNormalize( %vector );

%axis = vectorCross( %vector, %normal );
%angle = vectorDot( %vector, %normal );

return %axis SPC %angle;
}

Code: [Select]
function vectorToAxis( %vector )
{
%axis = vectorCross( %vector, "0 0 1" );
%angle = vectorDot( %vector, "0 0 1" );

return %axis SPC %angle;
}

Code: [Select]
function vectorToAxis( %vector )
{
%angle = mAtan( getWord( %vector, 1 ), getWord( %vector, 0 ) );
return "0 0" SPC %angle SPC 1;
}

Er, nevermind, I've managed to get it working by stitching together some resources from various places.

Code: [Select]
function vectorToAxis( %vector )
{
%pi = 3.1415926535897932384626433;

%x = mASin( getWord( %vector, 0 ) ) * 180 / %pi;
%y = mACos( getWord( %vector, 1 ) ) * 180 / %pi;

%angle = 180 - mFloatLength( %x / mAbs( %x ), 0 ) * ( 180 - %y );
%euler = vectorScale( "0 0" SPC %angle, $pi / 180 );
%matrix = matrixCreateFromEuler( %euler );

return getWords( %matrix, 3, 6 );
}

It only handles Z rotation, but that's fine for my use case.

Is that level of detail on Pi even meaningful? I usually stop at the second 5, and even that is dropped by Torque.

Try this.

Code: [Select]
function vectorToAxis( %vec )
{
%x = getWord( %vec, 0 );
%y = getWord( %vec, 1 );

%yawAng = mAtan( %x, %y );

if( %yawAng < 0.0 )
{
%yawAng += $pi*2;
}

%rot = "0 0 1" SPC %yawAng;

return %rot;
}

You should always double check your code against some known value. For instance we know that vector 0 1 0 is equal to the rotation of 1 0 0 0 or north. We can test this by setting our transform to be "0 0 0 1 0 0 0" then returning our forward vector.

I believe he wants to have the object spawn rotated in three dimensions to face a given point, not just rotated in two.
I could be mistaken about that, though.

What's with the sudden fascination with rotating objects to face others? I'll get Truce to post his solution here or ask Dotdotcircle for whatever he came up with.

You should put in more default Vector functions Rot.
Also something to make players look at a certain point ;)

I believe he wants to have the object spawn rotated in three dimensions to face a given point, not just rotated in two.
I could be mistaken about that, though.

Rotondo's solution works perfectly for my usage scenario.