- Home /
transform.up flips gameobject by it's x-axis when transform.up.x is 0 and when transform.up.y is negative
I have a 2D space shooter that has enemies with a script that makes the enemies look at the target and moves forward. I looked at specific ways on the internet that you could have the enemy gameobject look towards the target in a 2D setting and I ended up using
 transform.up = target.position - transform.position
It works just fine until transform.up.x ends up being 0 (Or somewhat very close to 0 like 0.00001) and transform.up.y is negative. This will cause the sprite to flip 180 degree on it's x-axis which is not what I want. How do I prevent this?
I found ways to work around this problem such as
 if (transform.up.x < 0.01f && -0.01f < transform.up.x)
           {
               transform.up.x = 0.01f;
           }
But this seems pretty silly for me to do. I could also use Atan2 to rotate the enemy to the target but I don't want to call Atan2 constantly in the Update method. I could also do this
 if (transform.rotation.x == 1)
           {
                 transform.rotation = Quaternion.Euler(0, 0, 180);
           }
I think this is the best solution out of all, but I still think that there has to be a better solution to this.
Enemy script:
 void Update()
 {
     transform.Translate(Vector2.up * speed * Time.deltaTime);
     transform.up = target.position - transform.position;
 }
 
 
Your answer
 
 
             Follow this Question
Related Questions
Hello, Need some help with Enemy facing the player on z axis !! 0 Answers
Simple Script Problem 1 Answer
How to make AI look at player 0 Answers
2D rotation question 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                