Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Detect where the enemy is facing using Vector3.Agnle or Dot only "Y" axis rotation?

Discussion in 'Scripting' started by GameDeveloperAf, Feb 1, 2022.

  1. GameDeveloperAf

    GameDeveloperAf

    Joined:
    Jul 3, 2020
    Posts:
    71
    I make AI system and I wanna know where enemy is facing depending on me. And I use Vector3.Angle. It works well, but I wanna check this value only with "Y" axis rotation. But this line of code works with "X" and "Z" axis rotations too. How can I disable "X" and "Z" axis rotation? Just I wanna get "Y" axis rotation value.

    Code (CSharp):
    1. float angle = Vector3.Angle(enemy.transform.forward, transform.forward);
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    I'm not 100% positive this is what you want, but one way is to "flatten" the vectors before you use them.

    Code (csharp):
    1. // copy original vectors out
    2. Vector3 enemyForward = enemy.transform.forward;
    3. Vector3 myForward = transform.forward;
    4.  
    5. // flatten in Y since we want angle around Y:
    6. enemyForward.y = 0;
    7. myForward.y = 0;
    8.  
    9. // now do your angle computation above:
    10. float angle = Vector3.Angle( enemyForward, myForward);
    Is that what you are trying to do? It makes the two vectors exist only in the flat plane X/Z.
     
    GameDeveloperAf likes this.
  3. GameDeveloperAf

    GameDeveloperAf

    Joined:
    Jul 3, 2020
    Posts:
    71
    Still, it is not like how I want. I posted a video to show a problem. Y rotates well, but X axis still change the value of the angle. I want to disable X and Z axes calculation. Z is disabled, but X axis still change the value of the angle. This code is good for flat plane, but for terrain or other surface it is not good, because of the X axis calculation. Is there any way to solve this problem? Also I used Dot, but still no hope.

    Code (CSharp):
    1. // It did not work. Stil X axis change the value of angle
    2. enemyForward.y = 0;
    3. myForward.y = 0;
    4.  
    Video starts at 0:14

     
  4. GameDeveloperAf

    GameDeveloperAf

    Joined:
    Jul 3, 2020
    Posts:
    71
    If anyone knows how to solve this issue, please help me.