I’ve been trying to improve my enemy AI for past few days, I’m working on a horror-obby game, where monsters detect players and then start chasing them, I have one problem that confuses me a lot
How I can raycast from a angle? I tried so many ways, using LookVector but it doesnt seem to be working
I want to raycast from an angle just like in this example picture I made to visualize what I’m talking about (red lines are raycast):
local numberOfRays = 20
local rayDistance = 20
local angleStep = 90 / (numberOfRays - 1)
local direction = humanoidRootPart.CFrame.LookVector
for i = 0, numberOfRays - 1 do
local angle = -45 + (angleStep * i)
local rotation = CFrame.Angles(0, math.rad(angle), 0)
local rayDirection = (rotation * direction).Unit
local rayOrigin = humanoidRootPart.Position + direction * 1.5
local hit = workspace:Raycast(rayOrigin, rayDirection * rayDistance)
if hit then
print("Hit object: " .. hit.Instance.Name)
else
print("No hit")
end
end
don’t forget to add raycastparams for the parts, otherwise they would be hitting each other
local function createRayPart(origin, direction)
local rayPart = Instance.new("Part")
rayPart.Size = Vector3.new(0.1, 0.1, rayDistance)
rayPart.Anchored = true
rayPart.CanCollide = false
rayPart.Color = Color3.new(1, 0, 0)
rayPart.Material = Enum.Material.Neon
rayPart.CFrame = CFrame.new(origin + direction * (rayDistance / 2), origin + direction)
rayPart.Parent = workspace
end
-- and in the for loop, just call it
createRayPart(rayOrigin, rayDirection)