Search Unity

Object's rotation from another relative to forward

Discussion in 'Scripting' started by FisherM, Dec 17, 2014.

  1. FisherM

    FisherM

    Joined:
    Dec 28, 2013
    Posts:
    366
    I am setting up a combat system and I have a List of GOs surrounding the player, the player has a list of attacks which have various Extreme Left and Extreme Right Angles that define how far the object can be to the left or right in degrees and the attack still connects here is an image if it helps.

    Regardless of the code I have now how can I check as an If statement condition that an object is within x left of the center and y degrees right of the FORWARD.
     
    Last edited: Dec 17, 2014
  2. darkAbacus247

    darkAbacus247

    Joined:
    Sep 7, 2010
    Posts:
    251
    Hey!
    This should be everything you need to get yourself going, Link

    Without having actually set it up, I imagine you're going to want to shoot a ray to the surrounding enemies, or enemies that fall within a given range. Such as a overlap sphere. Then using this ray get the angle between it and your players visual radius...etc.

    Much luck
     
  3. FisherM

    FisherM

    Joined:
    Dec 28, 2013
    Posts:
    366
    I already have the rest of the code, how can I calculate the angle being left or right
     
  4. darkAbacus247

    darkAbacus247

    Joined:
    Sep 7, 2010
    Posts:
    251
    You'll need to incorporate something like this into your current code.
    Otherwise, without having the code you're mentioning...I don't know?
     
  5. BenZed

    BenZed

    Joined:
    May 29, 2014
    Posts:
    524
    Code (CSharp):
    1.     protected float AngleBetweenPoints(Vector2 a, Vector2 b) {
    2.         return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
    3.     }
    4.  
    5.     public bool PointWithinForwardAngleRange(Vector2 point, float left, float right) {
    6.    
    7.         float angle = transform.rotation.eulerAngles.z;
    8.  
    9.         float relativeAngle = AngleBetweenPoints(point, transform.position) - angle;
    10.  
    11.         //Convert the rotation to be between -180 and 180 rather than 0 and 360
    12.         if (relativeAngle <= 180f) {
    13.             relativeAngle += 180f;
    14.         }
    15.  
    16.         //Angles below zero would be to the right of forward
    17.         if (relativeAngle < 0f) {
    18.             return Mathf.Abs (relativeAngle) <= right;
    19.         } else {
    20.             return relativeAngle <= left;
    21.         }
    22.     }
    These two functions should do it.

    Working example enclosed in a scene as a unity package. If the line coming out of your character pointing to the dummy turns green, it's within the specified left/right range.
     

    Attached Files: