- Home /
C# How to get a direction of a moving object?
So basically I'm doing a 2D-game which is from top-view and because I am pretty new to Unity and scripting in general, I don't have a clue how do I get the direction of a moving object (in this case, an enemy) so I can animate it.
I just want to know how do I know whether the object is going up, down, left or right.
This is my script at the moment. I really appreciate every helping comment, but most of all I would like to know the easiest way to know the direction.
int movementSpeed = 3; float detectionRange = 3f; Transform playerTransform; Transform myTransform;
 void Awake ()
 {
     myTransform = transform;
 }
 // Use this for initialization
 void Start () {
     playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
 }
 // Update is called once per frame
 void Update () {
     if (Vector3.Distance(playerTransform.position, myTransform.position)<detectionRange)
     {
         //goes to the players' direction
         Vector3 dir = playerTransform.position-myTransform.position;
         dir.Normalize();
         myTransform.position += dir * movementSpeed * Time.deltaTime;
     }
 
 }
Answer by Jeff-Kesselman · Jun 05, 2014 at 06:43 PM
dir is your movement direction as a normalized vector.
SO there are a few ways to get the cardinal direction. The simplest is to test the sign of dir.x and dirty.
Assuming a 2D coordinate system with origin ion the bottom left corner...
Neg Y means you are moving up, Pos Y means you are moving down Neg X means you are moving left, Pos X means you are moving right
Oh, thanks! I feel so stupid now since this was so obvious! But thank you!
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                