How do I convert a normal to a scale?

So, say I had a normalized direction and wanted to extend it’s magnitude to the face of a cube, how would I do that without physics raycasting?

To try to explain this better, how would I take Vector3(1,1,1).normalized and convert it back to Vector3(1,1,1)?

Gotcha.. yeah.. I shouldn't have downvoted him with such a poorly written question. Webert: I upvoted you just for the effort. Looks like you were just about to come up with the same solution. Thanks!

2 Answers

2

Just multiply the normalized vector by the magnitude you want it to have.

Vector3 vector = Vector3.one;
float magnitude = vector.magnitude;
		
// Vector will be what it originally was
vector = vector.normalized * magnitude;

But you see? This question is more complicated than how to change the magnitude. I'm trying to convert a radius magnitude to a magnitude that fits inside a cube. Make more sense?

Ah, I didn't get that from your question initially. I coded the following up in Unity to see if this would work (it does), then noticed @Bunny83 had already answered... anyway. Vector3 vector = Random.insideUnitSphere; float cubeSize = 5f; float magnitude = cubeSize / Mathf.Max(Mathf.Abs(vector.x), Mathf.Abs(vector.y), Mathf.Abs(vector.z)); // The vector will now lie on the cube of cubeSize vector = vector * magnitude;

It works like this:

  • figure out which component (x,y or z) has the greatest absolute value.
  • determine the factor which extends this component to 1 or -1 depending on the orientation. This is done by simply do f = 1.0f / x
  • multiply the whole vector by this factor.

So something like that:

// C#
Vector3 Cubify(Vector3 v)
{
    float f = Mathf.Max(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z));
    if (f == 0.0f)
        return Vector3.zero;
    return v / f;
}

That works perfect! It's funny you can google "cubify vector" and nothing shows up. I don't know what the technical term is really, but as long as it works, I'm happy. :D