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.
- Get Player’s Forward Vector: Use the “Get Actor Forward Vector” node for the player.
- Get Player’s Location: Use the “Get Actor Location” node for the player.
- Get Enemy’s Location: Use the “Get Actor Location” node for the enemy.
- Calculate Direction Vector to Enemy: Subtract the player’s location from the enemy’s location using a “Vector - Vector” node.
- Normalize Both Vectors: Normalize the player’s forward vector and the direction vector to the enemy.
- Calculate the Dot Product: Use the “Dot Product” node with the two normalized vectors.
- Calculate the Cross Product: Use the “Cross Product” node with the two normalized vectors.
- Break the Cross Product Vector: Use a “Break Vector” node to get the Z component of the cross product result.
- 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.
- 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).
- 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: