I’m making a blocking system and need to check the angle between the attacker and the defender to know if the block should work or if damage should go through. What’s the best way to get this angle?
Use this function to get the angle between two vectors: Vector3 | Documentation - Roblox Creator Hub
The two vectors to check would be the character’s LookVectors
local attackerLookVector = attacker.HumanoidRootPart.CFrame.LookVector
local defenderLookVector = defender.HumanoidRootPart.CFrame.LookVector
local angleBetween = attackerLookVector:Angle(defenderLookVector)
okay, imagine you’re the hero, and a monster tries to attack you. You only want to block the monster’s attack if it comes from the front.
To check that, you look at two directions: the way you’re facing (called your LookVector) and the direction from you to the monster. If those two directions point mostly the same way, the monster is in front of you, and you can block. Otherwise, the monster hits you.
we can use something called a dot product to measure this. A dot product near 1 means the monster is right in front. Near 0 means the monster is to the side. Less than 0 means the monster is behind.
If you want to block attacks in a 120° cone in front, you check whether the dot product is greater than the cosine of 60 degrees.
local yourLook = you.HumanoidRootPart.CFrame.LookVector
local toMonster = (monster.HumanoidRootPart.Position - you.HumanoidRootPart.Position).Unit
local dot = yourLook:Dot(toMonster)
if dot > math.cos(math.rad(60)) then
print("You blocked the monster's attack!")
else
print("The monster hits you!")
end
And here’s how it looks from above:
Please let me know if that works for you! The Dot function is described in the docs shared by @WeeklyShoe
Try something like this!
local function isBlockSuccessful(attacker, defender, maxAngleDegrees)
local attackerPos = attacker.HumanoidRootPart.Position
local defenderPos = defender.HumanoidRootPart.Position
local directionToAttacker = (attackerPos - defenderPos).Unit
local defenderLookVector = defender.HumanoidRootPart.CFrame.LookVector
local dot = defenderLookVector:Dot(directionToAttacker)
local angle = math.acos(dot) -- radians
local angleDegrees = math.deg(angle)
return angleDegrees <= maxAngleDegrees
end
-- Usage:
local blockAngle = 90 -- block works if attacker is within 90 degrees in front of defender
if isBlockSuccessful(attacker, defender, blockAngle) then
-- apply block effect
else
-- apply damage normally
end
