- Home /
how to find forwards,right,up component of a velocity
I have the velocity of a 3d ball but need to have a way of getting the right component of it, like you do with transform.right ect. I need to add it as a force to my rigidbody. Here's a quick diagram to show you:
@tormentoarmagedoom @Pangamini Just ask me if you have anything else that you need in order to work this out.
Answer by Pangamini · May 24, 2019 at 08:28 AM
Ahh ok I see, you want the direction, not the velocity component. Well the tricky thing is, there are infinitely many vectors that are perpendicular to the velocity vector.
You can get what you want by doing Vector3.Cross(), the cross product of two vectors is always perpendicular to both of them (if they are not parallel, of course). So if you do Vector3.Cross(velocity, Vector3.up) the result should be parallel to the ground and point to the side of the ball (either left or right, depends on the order of vectors in the cross). Just keep in mind that this will fail if the ball moves straight up or down (result will be a zero vector)
Thanks would there be a simpler way to deter$$anonymous$$e whether it would go left or right?
Well, it will always go either left or right - so just try it and see where does it go :) I am not sure about the order of cross operands now.
Ok. Which ones would you cross to get the forwards or would that simply be the velocity itself?
@Panga$$anonymous$$i
well depends on how do you define 'forwards'. If you want a 'forward' that's also parallel to the ground, then, well, think. Cross gives you avector perpendicular to both operands. It would be possible to just take the velocity, set Y to zero, and normalize - or, take your RIGHT vector, cross it with VEctor3.UP - giving you a vector perpendicular to those two - a forward that's parallel to the ground
Answer by Hellium · May 24, 2019 at 08:32 AM
As indicated by Pangamini, having a "right" vector is not that obvious because there are technically and infinite number of possible vectors. Supposing you want a vector which is perpendicular to the velocity vector, and the most perpendicular to the Vector3.up
, you can do the following.
Vector3 forward = velocity.normalized;
Vector3 v = Mathf.Abs( Vector3.Dot( forward, Vector3.up ) ) > 0.95f ?
Vector3.forward :
Vector3.down;
Vector3 right = Vector3.Cross( forward, v );
Vector3 up = Vector3.Cross( forward, right );
The problem mentionned by Pangamini is handled by the ternary operator.