Why my raycasting gun not shooting from handle to mouse position

what wrong with my script that im made. Just im shoothing to random object and my gun not shoothing to mouse position

video with proof

and scripts

LocalScript:

local Tool = script.Parent
local Handle = Tool.Handle

local RS = game:GetService("ReplicatedStorage")
local Remotes = RS.Remotes
local GunEvent = Remotes.GunEvent

local Player = game:GetService("Players").LocalPlayer
local Mouse = Player:GetMouse()

local startPos = Handle.CFrame.Position
local endPos = Mouse.Hit.Position

local Max_Distance = 1000


Tool.Activated:Connect(function()
GunEvent:FireServer(startPos,endPos,Max_Distance)
end)

ServerScript:

local RS = game:GetService("ReplicatedStorage")
local Remotes = RS.Remotes
local GunEvent = Remotes.GunEvent


GunEvent.OnServerEvent:Connect(function(Player,startPos,endPos,Max_Distance)
local RayCast = Ray.new(startPos,(endPos - startPos).Unit * Max_Distance)

local part,Position = workspace:FindPartOnRay(RayCast,Player.Character,false,true)

local laser = Instance.new("Part",workspace)

laser.BrickColor = BrickColor.new("New Yeller")

laser.Material = Enum.Material.Neon
laser.Transparency = 0
laser.Anchored = true
local distancePart = (startPos - Position).magnitude
laser.Size = Vector3.new(0.3,0.3,distancePart)
laser.CFrame = CFrame.new(startPos,Position) * CFrame.new(0,0,-distancePart / 2)

game:GetService("Debris"):AddItem(laser, 0.1)

end)
1 Like

You need to initialize endPosition on your localscript when the player clicks, not when the script runs. Currently, you’re creating it and setting it only once.

On another, unrelated note, I suggest using UserInputService instead of Mouse. It’s better practice, and Mouse doesn’t work well on other devices, such as mobile.

1 Like

Also I’d recommend processing the max distance on the server to prevent exploiters sending very high values to the server for an advantage

Its works, Thanks. And i added few more things
I comming soon fix problem with mobile and other devices problem

Tool.Activated:Connect(function()
local startPos = Handle.CFrame.Position
local endPos = Mouse.Hit.Position
GunEvent:FireServer(startPos,endPos,Max_Distance)
end)

oh, ok, but how do I change a variable to another tool when I’m creating new weapons

You could make a lookup table for any gun variables using a dictionary, with all the different tool names as keys.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.