- Home /
Direction of rigidbody.velocity.magnitude
I have a ridigbody that I move with AddForce. Then I read the speed with: rigidbody.velocity.magnitude
That gives me the speed in meters per second. Splendid! But now, I need to know if the speed (of a vessel) is forward or astern. The magnitude always returns a positive speed, but when astern, I need to read it as a negative speed.
I am sure that it is a very simple question but I can't find the answer anywhere. Thanks in advance.
Cheers, Michel
Answer by Bunny83 · Dec 16, 2012 at 02:34 PM
@XienDev is right.
The easiest way to get the velocity relative to your object is:
var localVel = transform.InverseTransformDirection(rigidbody.velocity);
now localVel.z is the local z axis velocity part which will be positive when moving forward and negative when moving backward. Furthermore you have localVel.x which is the sideward speed (positive == moves right, negative == moves left) and localVel.y which is the up / down speed (positive == up, negative == down).
Thank you both for your answers. Just out of curiosity, how did you get to know about something like, InverseTransformDirection? I have been working for more than 10 years with Flash ActionScript and now, I start with Unity, an excellent tool but I find the scripting ... a bit cryptic! ;-)
Cheers, $$anonymous$$ichel
Actually that's basic 3D stuff ;) I never really used Flash (only a bit AS2 back the old days :D). To me most AS stuff looks cryptic ;) Anyway here's the AS3 equivalent: globalToLocal
Ins$$anonymous$$d of InverseTransformDirection you could also use the worldToLocal$$anonymous$$atrix.
That's all pure vector math. (This is actually the moment your math $$anonymous$$cher was talking about.) Those functions exist in almost every game engine. The concept and the names of those functions might vary, but if you have understand what it does, the name of a function should give you an idea ;)
Just browse the docs on the major classes components just to see what a class is offering.
Here's a list of the most important components:
All sorts of Colliders
All sorts of Renderer
Or in general the class hierarchy
Some important or useful non component classes:
GUI, GUILayout, the Event class and the OnGUI callback
I could mention a lot more, but it depends on your needs. Physics, Networking, Pathfindng, dynamic object creation there are tons of untility classes and functions in the Unity API. Just search and you'll find ;)
Thank you Bunny. I know that I have to do a lot of reading but ... I am 64 years old and when you will be my age ... you'll understand why I am happy that I still know how to switch on my computer ... most of the time! LOL!
Answer by XienDev · Dec 16, 2012 at 02:10 PM
rigidbody.velocity - it's velocity vector in world space, magnitude - it's length
Your answer
![](https://koobas.hobune.stream/wayback/20220613085512im_/https://answers.unity.com/themes/thub/images/avi.jpg)