I want to be able to use raycasting to create a large radius for detecting parts, but I want it to form a sphere instead of a single direction. I found this function on stack exchange:
for i, obj in pairs(objects) do
local d = radius + obj.size
local dx = obj.x - centre.x
local dy = obj.y - centre.y
local dz = obj.z - centre.z
local sqrdist = dx * dx + dy * dy + dz * dz
if sqrdist <= d * d then
table.insert(hits, obj)
end
end
return hits
end
the post didn’t provide a lot of information about implementing it. if this function does create a ball of rays could someone show me how I can use it properly?
I believe using rays to make something like that may be straining to the server, and without actually knowing why you’d like to use it, I can’t really help.
I want to create a turret with some way of detecting things from a distance.
I cant use region3 because region3 cant be moved or deleted as far as I know.
I dont want to use a physical part to represent range because the turret needs to remain a single part and cant be part of a model.
I also read that casting rays isn’t very demanding performance-wise as you can cast hundreds of rays without destroying performance. that is why I would like to use raycasting to accomplish my goal.
You can compare the distance between the turret and all the targets first then cast a ray afterwards.
Trust me, comparing the distance between 2 vectors is really not expensive, even 50 targets a second.
Using rays to create a sphere is redundant. Just use magnitude to find the distance between the target and turret. If the turret isn’t controlled by a player the use of rays is pointless.
local Range = 50
local Targets = {}
local Players = game.Players:GetPlayers()
for i = 1, #Players do
local Character = Players[i].Character
if Character then
table.insert(Targets, Character.HumanoidRootPart)
end
end
-- This is not a reliable method to efficiently get all the targets, you need to add PlayerAdded, CharacterAdded and Humanoid.Died events to add and remove targets from the table
while Turret do
local Closest
for i = 1, #Targets do
local Target = Targets[i]
if not Closest then
if (Target.Position - Turret.Position).Magnitude <= Range then
Closest = Target
end
else
if (Target.Position - Closest.Position).Magnitude < (Closest.Position - Turret.Position).Magnitude then
Closest = Target
end
end
end
FireTurretAt(Target)
wait(Cooldown)
end
This is for the magnitude check, you can handle the list of targets you want and put them in a table then iterate through all of them.
this would be perfect for detecting characters, but I also want to get specific parts that are also spawned later in the game by the player, would it be ok to get the children of the whole workspace and filter it from there?