Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

know to which direction Vector.MoveTowards is moving unity 2D

Vector2 v = target_position - current_position; //Get our target and current positions (this.gameObject.transform.position).
float a = Mathf.Atan2(v.y, v.x) * Mathf.Rad2Deg; //Use Mathf.Atan2 method to get the radians.
//This will give you the radians of the +x axis in 2d. So 0 means it's facing right, pi is left, pi/2 is down, and 3pi/4 is up.
//Then multiply it with Mathf.Rad2Deg, which will give us degrees, and then it'd be 0, 180, 90, and 270 respectively.
int index = (int)((Mathf.Round(a / 90f) + 4) % 4); //Round off to the nearest 90 degree to eliminate diagonal movement.
//If you want diagonal, skip it. ^^

//After all this, index will be - 0 for right - 1 for up - 2 for left - 3 for down 
//Finally set your animations with if(index == 1){ //etc...
Source by forum.unity.com #
 
PREVIOUS NEXT
Tagged: #direction #moving #unity
ADD COMMENT
Topic
Name
2+6 =