I have the following three vectors:

  • posA: (1,2,3)
  • normal: (0,1,0)
  • offset: (2,3,1)

I want to get the vector representing the position which is offset in the direction of the normal from posA.

I know how to do this by cheating (not using matrix operations):

Vector3 result = new Vector3(posA.x + normal.x*offset.x
                             posA.y + normal.y*offset.y,
                             posA.z + normal.z*offset.z);

I know how to do this mathematically Note: [] indicates a column vector, {} indicates a row vector

result = [1,2,3] + {2,3,1}*{[0,0,0],[0,1,0],[0,0,0]}

What I don't know is which is better to use and if it's the latter how do I do this in unity? I only know of 4x4 matrices in unity. I don't like the first option because you are instantiating a new vector instead of just modifying the original. Suggestions?

Note: by asking which is better, I am asking for a quantifiable reason, not just a preference.

  • \$\begingroup\$ I'd say that doing it only with a Vector3 in this case is better, as it will be faster than transforming it by a matrix. \$\endgroup\$
    – Nic Foster
    Apr 13 '12 at 18:08

Hate answering my own questions, but here is what I did to solve this:

Unity has Vector3.scale. I assumed this was just scalar multiplication, but instead it's component-wise multiplication of vectors which is what I was doing with the matrices. The Vector3 class already has the + operator for component-wise addition, so this got really easy.

Vector3 result = posA + Vector3.Scale(normal,offset);

Haven't tested it, but it looks right

Though, I'm assuming the scale method is implemented using the exact code from my first example, at least it's cleaner now. I may write a method that uses references to modify the passed parameter so I'm not creating new instances just for this.

  • \$\begingroup\$ Don't hate your own answers. SE sites are good because others come later and say "hey, he solved my problem, +1" \$\endgroup\$
    – ashes999
    Apr 13 '12 at 19:46
  • \$\begingroup\$ You can use Matrix4.TRS if you want to operate directly on the Matrix4. unity3d.com/support/documentation/ScriptReference/… \$\endgroup\$
    – Chuck D
    Apr 13 '12 at 20:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .