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

How do I fix this straight-firing raycasting gun?

Asked by 4 years ago
Edited 4 years ago

Hey, all.

I'm making a gun system where a ray will be cast straight out of the muzzle, and stop when it hits a wall. Basically, how a gun would actually fire.

However, the math is odd, and the ray stops exactly one stud out from the target. If I try multiplying, the ray will go through all parts.

Here's the local script.

local function Shoot()
    local fromPoint = script.Parent.ForBullets.Position
    local direction = script.Parent.ForBullets.CFrame*CFrame.Angles(0,math.rad(0),0).LookVector

    game.ReplicatedStorage.Damage10Event:FireServer(fromPoint, direction)
end

And the server script.

game.ReplicatedStorage.Damage10Event.OnServerEvent:Connect(function(Player, FromPoint, direction)
    local RayCast = Ray.new(FromPoint, (direction - FromPoint))
    local part, Position = game.Workspace:FindPartOnRay(RayCast, Player.Character)
    local Laser = Instance.new("Part")
    Laser.Parent = game.Workspace
    Laser.CanCollide = false
    Laser.Anchored = true
    Laser.Material = Enum.Material.Neon
    Laser.Color = Color3.fromRGB(243,236,24)
    local Dist = (direction-FromPoint).Magnitude
    Laser.CFrame = CFrame.new(FromPoint, Position)*CFrame.new(0,0,-Dist/2)
    Laser.Size = Vector3.new(0.2, 0.2, Dist)
    game.Debris:AddItem(Laser, 0.05)
end)

I don't know how to do good raycasting math. Any help would be appreciated. (Also, I did look at other posts to figure this out. Still encountered problems.)

0
What about Ray.new( muzzle position, (muzzle position+ Vector3.new(0,0,-5)) - muzzle position).Unit * length of ray) royaltoe 5144 — 4y
0
Show your script with multiplication in it as well ankurbohra 681 — 4y
0
The issue is finding the length of the ray. As said above, it only goes one stud then stops. zhendirez 2 — 4y

Answer this question