I need to know if an object moves along its local horizontal axis, and I need to determine by how much it moves. The object can be oriented in any way in world space, and has no parent transform. So the transform’s forward Vector might be (0.541728, 0, 0.8405539), for example. Now the object is moved in any direction, and I want to know how many units it has been moved along its local X axis in the next frame.
It’s late and there might be a very simple solution, I just can’t think of it.
Then you only get the information if it moved right/left GLOBALLY.
After some time playing around I found the solution (it’s actually pretty simple):
void Update
{
var axis = transform.right;
var currentPosition = transform.position;
var delta = currentPosition - _previousPosition;
var magnitude = delta.magnitude;
var dot = Vector3.Dot(axis, delta.normalized);
_valueIWasLookingFor= dot * magnitude;
_previousPosition = currentPosition;
}
The dot product tells me about the orientation of my vector. So if I have a delta vector between my currentPosition and my previousPosition, I can use the dot product to see its orientation compared to my right vector. If it’s 1, it’s parallel, so I was moving exactly from left to right. If it’s -1, it’s opposite, so I was moving exactly from right to left. And if it’s 0, I was moving exactly orthogonal to it. I then multiply the magnitude of my delta vector with the result of the dot product, and I get the value I was looking for: how much did I actually move along the right/left.