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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

An ugly fire-arc-checking function

Discussion in 'Scripting' started by Smingleigh, Sep 21, 2015.

  1. Smingleigh

    Smingleigh

    Joined:
    Nov 24, 2012
    Posts:
    9
    I have a rather ugly C# function that determines if a turret with a limited fire arc is allowed to rotate far enough to shoot at a target. I'm posting this for two reasons: Firstly, I'd like to see if someone has a better solution, since this feels clumsy to me. Secondly, I haven't found accessible code for this purpose, which seems like it should be a fairly common one, so someone might stumble across this and find it useful.

    There is a Transform called turretBase, and its forward is the line against which its rotation limits are defined, in the up, down, left, and right directions. It checks to see if the local angle to the direction to the world-position argument is within the bounds of the rotation limits. I can't just use a single Vector3.Angle check because I am defining each direction's limit separately.

    Code (csharp):
    1.  
    2.     public bool TargetIsInArc(Vector3 pos)
    3.     {
    4.         Vector3 dir = turretBase.InverseTransformDirection(pos - turretBase.position);
    5.         float   turnLimit  = dir.x < 0 ? leftRotationLimit : rightRotationLimit;
    6.         float   pitchLimit = dir.y < 0 ? downRotationLimit : upRotationLimit;
    7.         bool    canSee = (Vector3.Angle(Vector3.forward, new Vector3(dir.x, 0, dir.z)) <= turnLimit
    8.                           &&
    9.                           Vector3.Angle(Vector3.forward, new Vector3(0, dir.y, dir.z)) <= pitchLimit);
    10.  
    11.         Debug.DrawLine(turretBase.position,
    12.                        pos,
    13.                        canSee ? Color.green : Color.red,
    14.                        Time.deltaTime);
    15.  
    16.         return canSee;
    17.     }
    18.  
    So, any suggestions?
     
    Last edited: Sep 21, 2015
  2. vintar

    vintar

    Joined:
    Sep 18, 2014
    Posts:
    90