Hi, Tophat here.
I’m working on a weapon system involving some guns. I’ve been wondering on how to cast rays that would be slightly inaccurate to it’s target (like a few degrees off)
Here is an crude diagram explaining what I’m trying to achieve:
A marks the gun’s end where the ray’s origin will be cast.
B marks the target where the player is aiming with the gun.
C would be the “range of inaccuracy” where the ray’s direction may be altered by a few degrees (such as by 5 degrees) The ray can be casted so its direction will be anywhere from the top of the line on the left side of the diagram to the bottom.
So, I ask, how would I do such a thing? I am not that confident with casting rays and certain aspects of CFrames in general.
Below is the code I am using:
script.Parent.WeaponEvent.OnServerEvent:Connect(function(Player, FromP, ToP, Attachment0)
-- Casts the ray
local RayCast = Ray.new(FromP,(ToP-FromP).unit*100)
-- Finds the part and position of any object hit by the ray
local Part,Position,Normal = game.Workspace:FindPartOnRay(RayCast,Player.Character, false,true)
-- Distance value for part that will be created
local Dist = 300
-- Part that represents ray to do damage to humanoids, with a distance cap
local RaycastPart = Instance.new("Part")
RaycastPart.Parent = game.Workspace
RaycastPart.Anchored = true
RaycastPart.CanCollide = false
RaycastPart.Material = Enum.Material.Neon
RaycastPart.Color = Color3.fromRGB(255, 251, 203)
RaycastPart.Transparency = 1
RaycastPart.Size = Vector3.new(0.1,0.1,Dist)
RaycastPart.CFrame = CFrame.new(FromP,Position)*CFrame.new(0,0,-Dist/2)
game.Debris:AddItem(RaycastPart, 0.025)
script.Fire:Play()
-- Damages humanoid if part was a humanoid
if Part and Part.Parent:FindFirstChild("Humanoid") then
Part.Parent.Humanoid:TakeDamage(script:GetAttribute("Damage"))
end
-- Creates an attachment to create beam, which visualizes ray
local Attachment1 = Instance.new("Attachment", workspace.BeamAttacher)
Attachment1.Name = "RaycastBeamAttachment"
Attachment1.WorldPosition = Position
-- Creates the beam
local Beam = Instance.new("Beam", workspace.BeamAttacher)
Beam.Color = ColorSequence.new{ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 251, 203)), ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 251, 203))}
Beam.FaceCamera = true
Beam.Width0 = 0.1
Beam.Width1 = 0.1
Beam.LightEmission = 1
Beam.Transparency = NumberSequence.new{NumberSequenceKeypoint.new(0, 0.3), NumberSequenceKeypoint.new(1, 0.3)}
Beam.Attachment0 = Attachment0
Beam.Attachment1 = Attachment1
game.Debris:AddItem(Beam, 0.025)
game.Debris:AddItem(Attachment1, 0.025)
end)
Help is very much appreciated!