🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Vector/Math Question

Started by
2 comments, last by CTRL_ALT_DELETE 22 years, 9 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.
Advertisement
  Magnitude = sqrt( (x*x) + (y*y) );Direction = atan2(y, x);  


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

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