I figured out the very basics of raycasting and made a turrent shoot a character but I want to make it so it does not igonr walls. I keep having this issue where it would stop shooting but not when the wall is between the character and the turrent but when its at some random position next to it. So what I did was spawn in a part at the position that the ray intersects and object and um got this.
The ray keep on going in that very specific direction no matter where I moved the character . Can someone please help me with this?
Here is the Script (If you are wondering why it says that is must only shoot if there is a wall in between the character and the turrent it is because I wanted it to spawn the parts) :
local barrel = script.Parent
local bulletSpeed = 200
local damage = 1
local fireRate = 0.5
local range = 200
local bullet = game.ReplicatedStorage.Bullet
while wait(fireRate) do
local posibleTargets = {}
local target = nil
local distances = {}
for a , v in pairs(game.Workspace:GetChildren()) do
if v:FindFirstChild("Humanoid") and (v:FindFirstChild("Torso").Position - barrel.Position).Magnitude < range then
posibleTargets[a] = v.Torso
end
for i , distance in pairs(posibleTargets) do
distances[i] = (barrel.Position - distance.Position).Magnitude
end
table.sort(distances)
for b,torsos in pairs(posibleTargets) do
if (torsos.Position - barrel.Position).Magnitude >= distances[0+b] then
if distances[1+b] ~= nil and distances[0+b] ~= nil then
if (torsos.Position - barrel.Position).Magnitude < distances[1+b] then
target = torsos
end
else
target = torsos
end
end
end
end
local success,errormessage = pcall(function()
if (target.Position - barrel.Position).Magnitude < range then
local parameters = RaycastParams.new(barrel,target,game.Workspace:FindFirstChild("Bullet"),game.Workspace.AlreadyPro:FindFirstChild("Left Arm"))
parameters.FilterType = Enum.RaycastFilterType.Blacklist
local rayCastResult = game.Workspace:Raycast(barrel.Position,target.Position,parameters)
if rayCastResult then
local part = Instance.new("Part",game.Workspace)
part.Anchored = true
part.Position = rayCastResult.Position
part.Size = Vector3.new(1,1,1)
local success,errormessage = pcall(function()
barrel.CFrame = CFrame.new(barrel.Position,target.Position)
end)
--TARGET HAS BEEN FOUND!!
if target.Parent.Humanoid.Health > 0 then
local cloneOfBullet = bullet:Clone()
cloneOfBullet.Position = barrel.Position
cloneOfBullet.Parent = game.Workspace
cloneOfBullet.Velocity = barrel.CFrame.LookVector * bulletSpeed
cloneOfBullet.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
hit.Parent.Humanoid.Health -= damage
end
end)
end
end
end
end)
end
