Search Unity

Determining horizontal movement

Discussion in 'Scripting' started by WavyRancheros, Jul 25, 2017.

  1. WavyRancheros

    WavyRancheros

    Joined:
    Feb 5, 2013
    Posts:
    176
    Hi,

    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.
     
  2. Basen1

    Basen1

    Joined:
    Dec 19, 2016
    Posts:
    76
    I don't think there's any other way then to store the previous position and then just check how much it is now

    distance traveled along x = currentPos.x - previousPos.x
     
    LiterallyJeff likes this.
  3. WavyRancheros

    WavyRancheros

    Joined:
    Feb 5, 2013
    Posts:
    176
    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):

    Code (CSharp):
    1. void Update
    2. {
    3.      var axis = transform.right;
    4.    
    5.      var currentPosition = transform.position;
    6.      var delta = currentPosition - _previousPosition;
    7.  
    8.      var magnitude = delta.magnitude;
    9.      var dot = Vector3.Dot(axis, delta.normalized);
    10.  
    11.      _valueIWasLookingFor= dot * magnitude;
    12.  
    13.      _previousPosition = currentPosition;
    14. }
    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.