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

How to make bullet stop at what the raycast hit?

Asked by 2 years ago

So i'm trying to make a script that shoots a bullet whenever the gun fires, but I dont know how to make it so that the bullet stops at the hit target

local tool = script.Parent
local Handle = tool:WaitForChild("Handle")
local Shoot = tool:WaitForChild("Shoot")

local Debris = game:GetService("Debris")

local range = 100

local damage = 20
local headshotDamage = 40

Shoot.OnServerEvent:Connect(function(Player, mousePos, originPos)
    local Character = Player.Character
    local Humanoid = Character:WaitForChild("Humanoid")

    local bulletDirection = (mousePos - originPos).unit * range
    local midpointPos = originPos + bulletDirection / 2

    local raycastParams = RaycastParams.new()
    raycastParams.FilterDescendantsInstances = {Character, workspace:WaitForChild("Bullets")}
    raycastParams.FilterType = Enum.RaycastFilterType.Blacklist

    local raycastResults = workspace:Raycast(originPos, bulletDirection, raycastParams)

    local bullet = Instance.new("Part", workspace:WaitForChild("Bullets"))
    bullet.BrickColor = BrickColor.new("Institutional white")
    bullet.Material = "SmoothPlastic"
    bullet.Name = Player.Name.."'s bullet"
    bullet.Transparency = 0.5
    bullet.Anchored = true
    bullet.Locked = true
    bullet.CanCollide = false
    bullet.CFrame = CFrame.new(midpointPos, originPos)
    bullet.Size = Vector3.new(.3,.3,bulletDirection.magnitude)

    Debris:AddItem(bullet, .75)

    if raycastResults then

        local ECharacter = raycastResults.Instance.Parent
        local EHumanoid = ECharacter:FindFirstChild("Humanoid")

        if EHumanoid and EHumanoid ~= Character then
            if raycastResults.Instance.Name == "Head" or raycastResults.Instance:IsA("Hat") then
                EHumanoid:TakeDamage(headshotDamage)
            else
                EHumanoid:TakeDamage(damage)
            end

            print(EHumanoid.Health)
        end
    end

    Shoot:FireClient(Player)
end)

Answer this question