How do I shorten the length of the ray in my raycast gun?

Local script:

local remote = game.ReplicatedStorage:WaitForChild(“Remotes”):WaitForChild(“GunEvent”)
local TweenService = game:GetService(“TweenService”)

remote.OnClientEvent:Connect(function(player, part, position, dist, barrelPos)

local bullet = Instance.new("Part")
bullet.Anchored = true
bullet.CanCollide = false
bullet.BrickColor = BrickColor.new("White")

bullet.Size = Vector3.new(0.05,0.05,dist)
bullet.Transparency = 0.8
bullet.Material = Enum.Material.Neon
bullet.CFrame = CFrame.new(barrelPos, position) * CFrame.new(0,0, -dist/2)

bullet.Parent = game.Workspace

game.Debris:AddItem(bullet, 0.25)

local Info = TweenInfo.new(

0.25,


Enum.EasingStyle.Cubic, 

Enum.EasingDirection.Out,

0, 
false,

0 

)

local Goals =

{

Transparency = 1;

}

local tween = TweenService:Create(bullet,Info,Goals)

tween:Play()

end)

Server script:

local remote = game.ReplicatedStorage:WaitForChild(“Remotes”):WaitForChild(“GunEvent”)

remote.OnServerEvent:Connect(function(player, barrelPos, mousePos)
local ray = Ray.new(barrelPos, (mousePos - barrelPos).unit * 100)
local part, position = game.Workspace:FindPartOnRay(ray, player.Character, false, true)

local dist = (barrelPos - mousePos).magnitude

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

remote:FireAllClients(player, part, position, dist, barrelPos)

end)

GIF of how ridiculously far the ray (bullet) shoots, I need it to be shortened: https://gyazo.com/5592d032dab231b6df49c70ce72912cd

This gun is nowhere near finished, I just need to fix this problem before I continue working on the other things. Thank you. Hopefully there should be an easy solution to it.

Reduce 100 to something like 50?

This line determines the length:
local dist = (barrelPos - mousePos).magnitude

You can use the function math.clamp to make sure the value stays in the size range you want. Therefore,
local dist = math.clamp((barrelPos - mousePos).magnitude, 0.05, 100)
will ensure that the bullet length is no higher than 100.

You also need to modify the ray check to avoid hitting players that are further away from the range of your weapon.

1 Like

I’ve tried that before, it doesn’t work. Thanks for trying to help though.

Your solution works, but one question, what does the 0.05 mean in local dist = math.clamp((barrelPos - mousePos).magnitude, 0.05, 100)?

It makes it so that the barrelPos - mousePos).magnitude value doesn’t go under 0.05 and never over 100.

1 Like

Ohhhhh, I get it now. Thank you.