Get further vector based on vector direction
I know it probably exists, but I can't find method or name of this operation. The thing is that vectors A and B are given. Based on their direction I want to calculate vector C that is alongside this imaginary line, further than vector B.
Answer by Adrian-S492 · Sep 01, 2020 at 07:17 AM
I was looking for a method or some kind of operation, but it turned out it's easier than I thought. In my case vector A was (0, 0, 0) so to get vector C i just need to multiply vector B by a certain number. If vector A is not Vector3.zero it's probably a little more complicated, but this idea still applies.
Yes, but if A is not the origin it's not really more complicated. All you do is remove A, scale your relative vector and add A back on ^^. In general if you do B - A
you get the relative vector from A to B. This you can scale as you want. The final result can simply be added back to A to get to point C.
C = A + (B - A) * scale;
In distinct steps it's usually more readable, expecially with longer / meaningful variable names:
Vector3 AB = B - A;
C = A + AB * scale;
Note that if you want the resulting relative vector to have a certain length, you can normalize it before you scale it. That way the vector AB will have the exact length you specify.
Vector3 AB = B - A;
C = A + AB.normalized * newLength;
Always keep in $$anonymous$$d that while code has to be readable / understandable by the compiler, it also should be readable and understandable by humans. The compiler doesn't care if you call your variable A, playerPosition or abz576eg5. A variable is just a variable. However you should write code that humans can understand easily. This is not only important when you work in a team where others might be watching or working on your code, but also for yourself. Try come back to more complicated code after a month, a year, ten years. If you have bad na$$anonymous$$g you will have a hard time to wrap your head around your own code.
Thanks for post, it's not much more complicated indeed. Of course na$$anonymous$$g convention is important, I just named this vectors as A, B, C so it's easier to create a scheme.
Your answer
Follow this Question
Related Questions
how to change the velocity of a rigid body based on a forward 0 Answers
Only limit player input and not external forces (Rigidbody 3D) 1 Answer
Predicting the hit point on X axis, based on vector direction 1 Answer
Finding Angle Between Vectors 1 Answer
c# help with rotate and rotatearound 0 Answers