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

How would I project the Ray Casting bullet from the gun so it's not a full laser?

Asked by 7 years ago

I'd like the bullet to be a limited length instead of being a massive line from the gun to the object, but can't figure out how. I'd appreciate some help.

Thanks for your time.

-Species

local tool = script.Parent
local player = game:GetService("Players").LocalPlayer

tool.Equipped:connect(function(mouse)
    print("Tool Equipped")

    local debounce = false

    mouse.Button1Down:connect(function(hit)
        if not debounce then
            debounce = true
            print("Mouse pressed!")
            local ray = Ray.new(tool.BulletExit.CFrame.p,(mouse.Hit.p - tool.BulletExit.CFrame.p).unit * 300)
            local part, position = workspace:FindPartOnRay(ray, player.Character, false, true)

            local beam = Instance.new("Part", workspace)
            beam.BrickColor = BrickColor.new("Really black")
            beam.FormFactor = "Custom"
            beam.Material = "Neon"
            beam.Transparency = 0.25
            beam.Anchored = true
            beam.Locked = true
            beam.CanCollide = false

            local distance = (tool.BulletExit.CFrame.p - position).magnitude
            beam.Size = Vector3.new(0.3, 0.3, distance)
            beam.CFrame = CFrame.new(tool.BulletExit.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)

            game:GetService("Debris"):AddItem(beam, 0.1)
            wait(.3)
            debounce = false

            if part then
                local humanoid = part.Parent:FindFirstChild("Humanoid")

                if not humanoid then
                    humanoid = part.Parent.Parent:FindFirstChild("Humanoid")

                end

                if humanoid then
                    humanoid:TakeDamage(15)
                end
            end
        end
    end)
end)

1 answer

Log in to vote
1
Answered by
AZDev 590 Moderation Voter
7 years ago

You will need to use a recursive ray cast.

You can take the distance from the muzzle of the gun and divide it by the number of raycasts per shot to find the length of each ray cast.

function RecursiveRaycast(Gun, Mouse, NumofRays) -- Gun: The muzzle, Mouse: The position of the mouse.
    LastPos = Gun
    for i = 1, NumofRays do
        local RRay = Ray.New(
            LastPos,
            Vector3.new(0, 0, LastPos.Z + Mouse.Hit.p.Z/NumofRays)
        )
        local Hit, Pos = workspace:FindPartOnRay(RRay, Character)
        if Hit then
            break -- Hit object stop raycast
            -- Check for human
        else
            LastPos = Pos
        end
    end
end

That's the basic concept. I haven't dealt with recursive raycasting for a very long time so chances are you're going to need to fix and modify some things. I wrote this in the browser so syntax errors are a great possibility.

Ad

Answer this question