Advertisement

Vector/Math Question

Started by September 30, 2001 03:25 PM
2 comments, last by CTRL_ALT_DELETE 23 years, 2 months ago
Let''s say I have the x and y componets of a vector, and I want to change its total Magnitude to 8(or any other number) while maintaing its current direction. How would I go about doing this? Thanks.
  Magnitude = sqrt( (x*x) + (y*y) );Direction = atan2(y, x);  


[Resist Windows XP''s Invasive Production Activation Technology!]
Advertisement

float myVec[ 3 ], mag;

mag = sqrt( myVec[ 0 ]*myVec[ 0 ] + myVec[ 1 ]*myVec[ 1 ] + myVec[ 2 ]*myVec[ 2 ] );

myVec[ 0 ] *= ( 8.0f / mag );
myVec[ 1 ] *= ( 8.0f / mag );
myVec[ 2 ] *= ( 8.0f / mag );




Normalising a vector reduces its magnitude to 1, so you can then multiply by 8 to get what you want. This gives the result that the AP showed. But that can be optimised:

ScaleFactor = 8.0f / sqrt(myVec[0]*myVec[0] + myVec[1]*myVec[1] + myVec[2]*myVec[2]);

myVec[0] *= ScaleFactor;
myVec[1] *= ScaleFactor;
myVec[2] *= ScaleFactor;

This topic is closed to new replies.

Advertisement