There are many similar topics (like this one), but I have found nothing about this specific part - horizontally.
I need to simulate a spending some travel points, but according to slopes angle. So, I have a normal points spending when I am traveling on a surface completely horizontal, and additional penalty spending when I am climbing on a slope. Therefore, I need to calculate it separately:
- Calculate the distance traveled horizontally.
- Calculate a penalty according to angle of the surface, which I am traveling on.
The first one is what I am interested in now. So, my approach is the following, with saving the last position:
Vector3 lastPosition;
void Update()
{
var difference = transform.position - lastPosition;
var horizontalProjection = Vector3.ProjectOnPlane(difference, Vector3.up);
var traveledHorizontally = horizontalProjection.magnitude;
lastPosition = transform.position;
}
And it seems like it works - traveledHorizontally is the actual path traveled horizontally every frame. The question is - is there any more compact and cheap calculations, or perhaps even a built-in solution?
I tried distance, but this is actually the distance in 3D space, not horizontally. And I can’t get a projection from this distance, because it is scalar.
var distance = Vector3.Distance(transform.position, lastPosition);
It seems like this distance is the magnitude of the difference between two vectors as in my approach, but I can’t get access to this vector to project it on a horizontal plane.
I tried also a magnitude of some horizontal movement acquired from the old input system, but the magnitude of the resulting vector is too big - it definitely not the actual distance traveled horizontally.
var horizontalMovement = transform.forward * Input.GetAxis("Vertical");
horizontalMovement += transform.right * Input.GetAxis("Horizontal");
var traveledHorizontally = horizontalMovement.magnitude;