I’m trying to make a ray gun using raycasting but most of the time, the ray doesn’t fire and the RaycastResult returns nil. (I can see because I put code in to visualize the beam)
I’m using Mouse:Hit() to determine the direction.
Here’s my code, I don’t know if it would help
Client
local tool = script.Parent
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local h = char:WaitForChild("Humanoid")
local animator = h:WaitForChild("Animator")
tool.Activated:Connect(function()
if tool.Enabled == true then
tool.Enabled = false
local mouse = plr:GetMouse()
local mousePos = mouse.Hit.Position
print(mousePos)
tool.Fire:FireServer(mousePos)
wait(1.5)
tool.Enabled = true
end
end)
tool.Fire.OnClientEvent:Connect(function()
local failAnim = animator:LoadAnimation(script.failAnim)
tool.Parent = plr.Backpack
failAnim:Play()
wait(1)
tool.Parent = char
failAnim:Stop()
end)
Server
local tool = script.Parent
local tweenService = game:GetService("TweenService")
function openDoor(ray)
local button = ray.Instance
button.BrickColor = BrickColor.new("Bright green")
local door = workspace.Doorway.Door
local info = TweenInfo.new(
3.5,
Enum.EasingStyle.Linear,
Enum.EasingDirection.In)
local goals = {
Position = Vector3.new(-25.96, 23.716, 60.5)}
local tween = tweenService:Create(door,tweenInfo,goals)
tween:Play()
end
tool.Fire.OnServerEvent:Connect(function(plr,hit)
local char = plr.Character
local h = char.Humanoid
local beam = script.RayBeam:Clone()
local originAttach = tool.Handle.OriginAttachment:Clone()
local ray = workspace:Raycast(originAttach.Position,hit)
if ray then
print(ray.Instance.Name)
tool.Handle.Fire:Play()
local position = ray.Position
local attach = Instance.new("Attachment")
attach.Name = "HitAttachment"
attach.Parent = workspace["Big ol Box"].Baseplate
attach.Position = position
originAttach.Parent = workspace["Big ol Box"].Baseplate
beam.Parent = workspace.Beams
beam.Attachment1 = attach
beam.Attachment0 = tool.Handle.OriginAttachment
if ray.Instance.Name == "Button" then
openDoor(ray)
end
wait(1.5)
beam:Destroy()
attach:Destroy()
originAttach:Destroy()
tool.Handle.Reload:Play()
else
print("Couldn't find where the ray hit :(")
tool.Fire:FireClient(plr)
end
end)
Is there anything I’m doing wrong? This is the first time I’m using raycasts, so I’m pretty new.