Search Unity

Question Flipping enmey on a certain angle.

Discussion in 'Scripting' started by mmntlh, May 27, 2020.

  1. mmntlh

    mmntlh

    Joined:
    Feb 2, 2019
    Posts:
    11
    Hi! I have an enemy which follows player and his weapon always aims at the player but after adding the aim feature the flipping is messed up now i want to flip the enemy when the rotation angle is 90 and -90 but I can't figure out it.

    upload_2020-5-27_16-40-18.png

    as you can you in the image above the rotation works on the gun but the parent sprite (Enemy) does not flip.

    But if i try to flip using the transform.local scale method:
    upload_2020-5-27_16-50-7.png
    Rotation is also inverted, I think.


    this was the flipping code i used before
    Code (CSharp):
    1.  public void Flip()
    2.     {
    3.  
    4.         if (player.position.x > transform.position.x)
    5.         {
    6.             //face right
    7.             transform.localScale = new Vector3(1, 1, 1);
    8.         }
    9.         else if (player.position.x < transform.position.x)
    10.         {
    11.             //face left
    12.             transform.localScale = new Vector3(-1, 1, 1);
    13.         }
    14.        
    15.     }
    Gun Aim At player code:
    Code (CSharp):
    1.  
    2.     public float speed = 0f;
    3.     public Transform target;
    4.     public float angle;
    5.  
    6.     public Enemy enemy;
    7.  
    8.     // Update is called once per frame
    9.     void Update()
    10.     {
    11.         if (target != null)
    12.         {
    13.             Vector2 direction = target.position - transform.position;
    14.             angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    15.             Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    16.             transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);
    17.  
    18.             enemy.Flip();
    19.  
    20.         }      
    21.  
    22.     }
    I think I will need to use those eular angles to flip the parent and rotate the gun but I don't know how! please help.