Gun scripting simple question

I’m currently using mouse.Target and mouse.Hit to determine where the gun shoots, but it seems to be a very unpopular choice. Is there a reason for this? Is there a possible downside?

The reason is that if you’re third person, you can move your mouse where the gun shouldn’t be able to shoot and shoot it through walls. For example, you can shoot by looking through a doorway or moving your camera through a window.

oh yeah lol mb

Do you know why this script isnt working then? It doesnt detect anything

local player = game:GetService("Players").LocalPlayer
local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(key, isTyping)
	if isTyping == false then
		if key.UserInputType == Enum.UserInputType.MouseButton1 and script.Parent.Parent == player.Character then
			local rayOrigin = player.Character.Head.Position
			local rayDirection = player:GetMouse().Hit.Position

			local raycastParams = RaycastParams.new()
			raycastParams.FilterDescendantsInstances = {script.Parent}
			raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
			raycastParams.IgnoreWater = true
			
			local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
			
			if raycastResult then
				print("yo")
				game.Workspace.Sphere.Position = raycastResult.Position
				if raycastResult.Instance.Parent:FindFirstChild("Humanoid") then
					raycastResult.Instance.Parent:FindFirstChild("Humanoid").Health -= 10
				end
			else
				print("nothing")
			end
		end
	end
end)
1 Like

This should be the problem, the direction should be a directional vector so I suggest doing this:

local rayDirection = CFrame.new(rayOrigin, player:GetMouse().Hit.Position).LookVector
1 Like

The naming of the rayDirection argument to workspace:Raycast causes a lot of confusion, because it’s reasonable to expect a parameter called “direction” to be a unit vector. However, what it actually expects is a vector that’s the length of the desired raycast, so you want:

local rayDirection = player:GetMouse().Hit.Position - rayOrigin

without .Unit added to it. You don’t need to construct a full CFrame in either case, that’s doing more calculations than you need.

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