Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I add a "spread" to this laser script?

Asked by 6 years ago

So, what I'm wondering is how I can make the end of the ray (goes to mouse position) offset randomly, so when the gun fires, the ray will have a "spread", similar to actual guns. I already know how to use math.random, but I do not know where, and how to add the offset to the end of the ray.

local ray = Ray.new(tool.Handle.CFrame.p, (mouse.Hit.p - tool.Handle.CFrame.p).unit * 2048)
        local part, position = workspace:FindPartOnRay(ray, player.Character, false, true)
        local beam = Instance.new("Part", workspace)
        beam.BrickColor = player.TeamColor
        beam.FormFactor = "Custom"
        beam.Material = "Neon"
        beam.Transparency = 0
        beam.Anchored = true
        beam.Locked = true
        beam.CanCollide = false
        local distance = (tool.Handle.CFrame.p - position).magnitude
        beam.Size = Vector3.new(0.1, 0.1, distance)
        beam.CFrame = CFrame.new(tool.Barrel.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)
        game:GetService("Debris"):AddItem(beam, 0.1)

1 answer

Log in to vote
0
Answered by
mattscy 3725 Moderation Voter Community Moderator
6 years ago
Edited 6 years ago

To get a random variation in the direction of the laser, you can multiply it by CFrame.Angles with random angles as the arguments. For example:

local Variation = 15

beam.CFrame = CFrame.new(tool.Barrel.CFrame.p, position) * CFrame.Angles(math.rad(math.random(-Variation,Variation)), math.rad(math.random(-Variation,Variation)), 0) * CFrame.new(0, 0, -distance/2)

this would rotate the beam up to 15 degrees on both the X and Y axes (you may have to swap the X with the Z if it rotates on the wrong axis). Basically, math.rad converts degrees to radians (which CFrame.Angles uses), and it's given a random number of degrees.

Hope this helps!

EDIT: to get more a more specific spread (like a hundredth of an increment), you can multiply by 100 before getting the random number and divide by 100 after. So, for example:

local Variation = 3

beam.CFrame = CFrame.new(tool.Barrel.CFrame.p, position) * CFrame.Angles(math.rad(math.random(-Variation*100,Variation*100)/100), math.rad(math.random(-Variation*100,Variation*100)/100), 0) * CFrame.new(0, 0, -distance/2)
0
This worked! Was very helpful. Just slightly curious on how I can get the number range into "0.1" increments (giving more freedom to spread, rather than just shoot at 3 different angles(I set it to 3, because 15 made the lasers spread so much, lol)) KingPig999 13 — 6y
0
Edited mattscy 3725 — 6y
Ad

Answer this question