# Calculate 4 way direction of movement for 2d object

Hello I have some code which uses velocity to tell which direction an object is moving. It does not always seem to work though and will sometimes say it is moving in the wrong direction. Any Advice? Thank You!

``````private var prevLoc : Vector3 = Vector3.zero;
var itsmoving = false;
var direction : String;

function Start () {

}

function Update () {

//if moving stuff
var curVel : Vector3 = (transform.position - prevLoc) / Time.deltaTime;
if ((curVel.z > 0) && ((curVel.z - curVel.x > 0))) {direction = "up";}
else if ((curVel.z < 0) && ((curVel.z - curVel.x < 0))){direction = "down";}
else if ((curVel.x > 0) && ((curVel.x - curVel.z > 0))){direction = "right";}
else if ((curVel.x < 0) && ((curVel.x - curVel.z < 0))) {direction = "left";}

if((curVel.z > 0) || (curVel.x > 0) || (curVel.z < 0) || (curVel.x < 0))
{
// it's moving !!!!
itsmoving = true;

} else if ((curVel.z == 0) && (curVel.x == 0)) {
// it's not moving
itsmoving = false;

}
prevLoc = transform.position;
}
``````

All those ifs are giving me a headache readability-wise so I ended up just thinking about it in a different way. You can do this quite easily by utilizing the dot products of vectors. In essence you can test with them if two vectors are “going in the same direction”, in which case the dot product is positive (if they’re going in separate directions the dot product is negative). Basically what you want to do is to just check:

``````var dotUp : float = Vector3.Dot(curVel, Vector3.whateverIsUp);
var dotRight : float = Vector3.Dot(curVel, Vector3.whateverIsRight);
if(dotUp > 0){
direction = "up";
} else if(dotUp < 0){
direction = "down";
} else if(dotRight > 0){
direction = "right";
} else if(dotRight < 0){
direction = "left";
} else {
direction = "not moving";
}

if(curVel.magnitude > 0){
itsmoving = true;
} else {
itsmoving = false;
}
``````

In this case I guess your “up” would be Vector3.forward and “right” would be Vector3.right. If you need help understanding how dot products work just ask.