Hi there, thanks for looking at my question.
As per the title, I’m having a bit of difficulty finding a reliable method of determining the direction an object is moving relative to itself. I’m not looking for a way to control an object or anything like that, but if an object is in motion already I need a way to determine the direction it’s headed relative to itself.
I need this so that no matter where it’s facing or what it’s doing relative to the camera or the world, if it moves sideways (relative to itself), my script will know it is doing so. Same goes for any other direction.
Right now I’ve cobbled together something using velocity, but it’s far from ideal as the numbers it gives me to work with are all over the place and unreliable for this type of thing.
Any help would be greatly appreciated.
Assuming you have a method of getting the world velocity such as Rigidbody.velocity, or comparing positions between frames, you can get the local velocity by using Transform.InverseTransformDirection(). For example:
var localVelocity = transform.InverseTransformDirection(rigidbody.velocity);
As for moving sideways, look at localVelocity.x. Negative values are left movement, positive values are right movement.
If you are calculating velocity yourself by comparing positions, you may want to average values over a number of frames.
let’s say your object is a car and you want to know the direction (going backwards, forward, sliding on the right etc…) right?
if so, you need two things;
- velocity of your object
- rotation of your object
with those you can do this;
theDirection = Quaternion.FromToRotation(object rotation * Vector3.up, Quaternion.identity * Vector3.up) * velocity
With these two, you would get a rotated vector of your velocity, to 0 rotation of your object.
this came later to my mind;
theDirection = Quaternion.Inverse(object rotation) * velocity
I hope this helps. good luck.
You can calculate the direction with the endposition and currentposition, its as easy as:
Endposition - currentposition = direction
Both end and current position are vector3