Unsure about problems with raycasting for a gun

Hello there; title really says it all.

The result I want from the system is for the raycast to properly go to the mouse’s cursor, but it instead goes behind the player;

Client

local event = script.Parent:WaitForChild("a")

local mouse = game.Players.LocalPlayer:GetMouse()

mouse.Button1Down:Connect(function()

event:FireServer(mouse.Hit.p)

end)

Server

local remoteEvent = script.Parent.a
local tool = script.Parent

-- min
-- max
min, max = 10, 20

local function takeDamage(humanoid)
	local random = math.random(min, max)
	humanoid.Health -= random
end

remoteEvent.OnServerEvent:Connect(function(plr, mouseHit)
	local startPosition = script.Parent.Handle.CFrame.Position
	local endPosition = mouseHit
	local newPos = (startPosition - endPosition)
	local rayParams = RaycastParams.new()
	rayParams.FilterDescendantsInstances = tool.Parent:GetDescendants()
	local rayCast = workspace:Raycast(startPosition, newPos)
	
	if rayCast then
		if rayCast.Instance.Parent:FindFirstChild("Humanoid") then
			local a = tool.Handle:Clone()
			a.Name = "mousePart"
			a.Position = rayCast.Position
			a.Anchored = true
			a.Parent = workspace
			takeDamage(rayCast.Instance.Parent:FindFirstChild("Humanoid"))
		end
	end
end)

yes i do know about the fact this can be mass spammed; i just want to fix the raycasting first

bumping cause i haven’t been able to fix

Switch startPosition and endPosition around on this line:

local newPos = (startPosition - endPosition)
1 Like

Okay, I’ll try that and see if it fixes the issue.

https://gyazo.com/1d506237d9cabe31f1db1e4c882f34c8

It has mostly fixed the issue; but it still spawns it inside of the character; is there any reason why this is happening?

(if needed i can provide an rbxm of the whole place)

It’s probably just the raycasting hitting yourself, I would just filter out your own character in the raycast.

2 Likes

I have already done that in the script; but idk if i’ve done anything wrong with the setup for it

Set it to plr.Character
Because the tool is under the character, it will be filtered too

Sorry for the late response, but it does seem to be working (now) properly as long as I dont move for some reason.

if i move the issue shown here occurs again