I want to make a gun script with raycasting but the raycast isn’t doing what I thought it would.
It is going in random directions that don’t match up with the mouse’s position at all.
here is my code:
local function createEffects(position)
local Part = Instance.new("Part", Tool)
local Att1 = Instance.new("Attachment", Part)
game:GetService("Debris"):AddItem(Part, 0.5)
Part.Position=position
Part.Transparency=1
Part.CanCollide=false
Part.Anchored=true
Att1.WorldPosition=Part.Position
Beam.Attachment1=Att1
Tool.Barrel.ParticleEmitter.Enabled=true
wait(0.5)
Tool.Barrel.ParticleEmitter.Enabled=false
end
local function shoot(plyr, mpos)
local ray = Ray.new(script.Parent.Barrel.Position, mpos)
local hit, position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent.Parent, script.Parent})
if hit then
local Humanoid = hit.Parent:FindFirstChild("Humanoid")
if Humanoid then
Humanoid:TakeDamage(25)
end
createEffects(position)
end
end
script.Fire.OnServerEvent:Connect(shoot)
First off, the beam is attached to a part, and you set the part’s position once in the beginning of the script. Therefore no matter which direction you face the beam will keep going to that single location. Secondly, could you proved the code that fires the remote event so that we can see how you calculate the position of the beam.
local Tool = script.Parent
local Fire = Tool.Script.Fire
Tool.Equipped:Connect(function(Mouse)
Mouse.Button1Down:Connect(function()
Fire:FireServer(Mouse.Hit.p)
end)
end)
The problem is that say your mouse is pointing at a wall that is 20x10 meters long, it will make the beam point to the center of that wall even though your mouse might be pointing toward the edge of the wall.
The problem is that once the remote event fires, the beam keeps pointing at the same wall, it doesn’t know to change it’s direction. I don’t know how to fix this other than constantly firing the server with the mouses updated position, but that could cause lag.