- Home /
Vector2 Normalize ?
There doesn't seem to be a normalize function for Vector2's.
If I use a 2D vector inside the Vector3.Normalize static function, will that deal with it happily? Similarly, if I set a 2D vector to a 3D one, how will it handle it? Just pass back the first two components (X and Y)?
i.e. is this valid:
Vector2 delta = vTo - vFrom;
//... ignore delta mangitude == 0.0f
Vector2 direction = Vector3.Normalize( delta );
Thanks in advance!
Answer by Herman-Tulleken · Aug 16, 2010 at 12:28 PM
It seems like it does work. I can't see by which mechanism this is possible (perhaps an auto-conversion). You could also use the following (it is probably faster):
Vector2 direction = delta.normalized;
Answer by Peter G · Aug 16, 2010 at 01:14 PM
Did you try casting? You cannot implicitly cast from Vector3 to Vector2 because you will lose the z value.
Vector2 direction = (Vector2)Vector3.Normalize(delta);
I actually want to lose the Z! The delta didn't have any in the first place in this example, so for all intents and purposes, it's just junk data. Obviously, that's inefficient, but it suits my purposes :). Thanks for this!
I guess casting is a better practice for this, just to keep the conversion explicit.
Oh, and I guess I probably want to cast the delta to a Vector3, also.
It's fine that you want to lose the z, but the compiler doesn't know that. It assumes that you are making a mistake and are going to accidentally throw away your z value so you even if you want to lose it, you have to tell it that.
Edit: you don't need to cast delta to a Vector3 because that's implicit. The z value is assumed to be 0.
Thanks Peter! I'll try to remember the implicit cast cases.
Answer by Wolfram · Aug 16, 2010 at 04:22 PM
You can help yourself with the .magnitude field, which is available for Vector2, so there will be (probably) no internal casting.
Vector2 delta = vTo - vFrom;
Vector2 direction = delta/delta.magnitude; // maybe test this for ==0 first
EDIT: To complete the answer: Vector3.Normalize(v) modifies and normalizes vector v. It does not return anything, so you can't use it at all here. Either use this method I described here, or use delta.normalized, as Herman Tulleken suggests.