so this is the code for my raycast
local ray = Ray.new(char:FindFirstChildOfClass("Tool").tool.barrel.Position,(pos).Unit *5)--starts the ray local hit = game.Workspace:FindPartOnRay(ray) if hit then print(hit," yay!") else print(hit," awww") end
it always prints nil awww even when i hit something and it is closer than 5 studs and at the thing im standing on too please help
fifkey i changed the raycast to this:
local ray = Ray.new(char:FindFirstChildOfClass("Tool").tool.barrel.Position,(pos-char:FindFirstChildOfClass("Tool").tool.barrel.Position).Unit *5)--starts the ray
it didn't work is there anything else i did wrong?
So this script basically gets the position from the camera to the point in world space and then makes a new ray from your gun barrel to where ever the click location is at. I have explained a bit more with comments.
local tool = script.Parent local UserInputService = game:GetService("UserInputService") local player = game.Players.LocalPlayer local Camera = workspace.CurrentCamera local equipped = false local character = player.Character:GetChildren() local toolOrigin = character:FindFirstChildOfClass("Tool").tool.barrel.Position local RE = game.ReplicatedStorage:WaitForChild("RemoteEvent1") tool.Equipped:Connect(function() equipped = true end) tool.Unequipped:Connect(function() equipped = false end) function getMouseHit(x,y) local ray = Camera:ScreenPointToRay(x, y, 0) local ray1 = Ray.new(ray.Origin,ray.Direction * 1000) local part, hitPos, norm = workspace:FindPartOnRayWithIgnoreList(ray1,character) return CFrame.new(hitPos,ray1.Origin)*CFrame.Angles(0,math.rad(180),0) end UserInputService.InputBegan:Connect(function(input, gameProcessed) if equipped and not gameProcessed and input.UserInputType == Enum.UserInputType.MouseButton1 then local worldCF = getMouseHit(input.Position.X,input.Position.Y) RE:FireServer(toolOrigin,worldCF,character) end end)
Server script:
local RE = Instance.new("RemoteEvent") RE.Name = "RemoteEvent1" RE.Parent = game.ReplicatedStorage RE.OnServerEvent:Connect(function(player,toolOrigin,worldCF,character) local ray = Ray.new(toolOrigin,(worldCF.Position-toolOrigin).Unit) local ray1 = Ray.new(ray.Origin,ray.Direction * 1000) local part, hitPos, norm = workspace:FindPartOnRayWithIgnoreList(ray1,character) if part then print(part," yay!") else print(part," awww") end end)
Make sure that the second value of Ray.new is a unit vector. A unit vector is a vector value with a magnitude of 1, used to indicate a direction. To make a unit out of two positions, you use (PositionB - PositionA).Unit
and multiply that value by a scalar (a number). If that's too complicated, you can also do CFrame.new(PositionA, PositionB).LookVector * Scalar
as well.