# How to Calculate Angle Between Player and Enemy and Check if Within Attack Range

Hi everyone,

I recently worked on a project where I needed to calculate the angle between the player and an enemy and then check if the enemy is within a specific attack range (e.g., 120 degrees in front of the player). After some trial and error, I managed to get it working and wanted to share the solution with you all, as I couldn’t find a comprehensive guide on this topic.

### Step-by-Step Solution

#### Step 1: Calculate the Angle

First, we need to calculate the angle between the player’s forward direction and the direction to the enemy.

1. Get Player’s Forward Vector: Use the “Get Actor Forward Vector” node for the player.
2. Get Player’s Location: Use the “Get Actor Location” node for the player.
3. Get Enemy’s Location: Use the “Get Actor Location” node for the enemy.
4. Calculate Direction Vector to Enemy: Subtract the player’s location from the enemy’s location using a “Vector - Vector” node.
5. Normalize Both Vectors: Normalize the player’s forward vector and the direction vector to the enemy.
6. Calculate the Dot Product: Use the “Dot Product” node with the two normalized vectors.
7. Calculate the Cross Product: Use the “Cross Product” node with the two normalized vectors.
8. Break the Cross Product Vector: Use a “Break Vector” node to get the Z component of the cross product result.
9. Calculate the Angle Using Atan2: Use the `Atan2Degrees` node with the Z component of the cross product as Y and the dot product as X.

#### Step 2: Check If Enemy is Within Attack Range

Once we have the angle, we need to check if it falls within the desired range.

1. Check if Angle is in Range: Use the “In Range Float” (mine is called SpellArea) variable to check if the angle is between -60 and 60 degrees (for a 120-degree attack cone).
2. Branch Node: Use a “Branch” node to perform actions based on whether the enemy is within the range.

Here’s the blueprint I made, I hope it helps:

• no need to normalise direction, it’s already normalised
• `Get Unit Direction` can shave nodes off your script
• no need for cross product unless you need left / right
• `Dot``aCOSd` is faster; or skip the degrees entirely and work with dot values directly
3 Likes

possibly even simpler, i just FindLookAtRotation, delta it from character rotation and can then split the pins, so if ABS Z is <= x its within that range

Thank you very much, that was exactly what I was looking for!