local tool = script.Parent
local function shoot()
local rayOrigin = tool.gun.Position
local rayDirection
local rayTarget = tool.Parent.Humanoid.TargetPoint
--Do a CFrame operation to determine the orientation to that point
local operationPart = Instance.new("Part")
operationPart.Transparency = 1
operationPart.CanCollide = false
operationPart.Anchored = true
operationPart.CFrame = CFrame.new(rayOrigin, rayTarget)
--Destroy the Operation Part, and cast the ray
rayDirection = operationPart.Orientation
print(rayDirection)
print(rayOrigin)
operationPart:Destroy()
local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {tool.Parent}
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
if raycastResult then
local hitPart = raycastResult.Instance
if hitPart:IsA("Part") then hitPart.BrickColor = BrickColor.Random() end
end
end
tool.Activated:Connect(shoot)
It’s supposed to change the BrickColor of any Part it hits. It used to work, but once I added the CFrame operation, it doesn’t work anymore.
A much simpler way to find the direction you want to give the ray, without all the complicated creation of parts and such, is a simple vector subtraction. Instead of all that code with operationPart, you can simply do rayDirection = (rayTarget - rayOrigin).Unit (and then multiply it by a magnitude as mentioned in the reply above mine)
The magnitude is in studs.
Taking a look at TargetPoint's documentation, Roblox recommends to avoid using it entirely because it doesn’t work anymore.
Instead you should separate this into two parts. A LocalScript will handle the input, detecting when the player clicks with the tool equipped, then sends the mouse information over to the server via RemoteEvent in order to have the server do the raycast and hit detection.