Linear Velocity changing speed depending on distance

I am using linear velocity for the first time to make a gun from scratch. I have it so a bullet shoots and goes in the right direction but the further away I want to shoot, the faster it gets and I just want a constant speed. Does anyone know how?

Server Code:

local repliStorage = game:GetService("ReplicatedStorage")
local event = repliStorage.Shoot

event.OnServerEvent:Connect(function(player, target, sp, handle)
	
	local bullet = repliStorage.Bullet:Clone()
	bullet.Parent = handle.Parent
	bullet.Position = sp
	
	local Attachment = Instance.new("Attachment", bullet)

	local LV = Instance.new("LinearVelocity", bullet)
	LV.MaxForce = math.huge
	LV.VectorVelocity = (target - sp) * 0.5
	LV.Attachment0 = Attachment
	
end)

Client Code:

local handle = script.Parent:WaitForChild("Handle")
local tip = handle:WaitForChild("Tip")
local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()
local repliStorage = game:GetService("ReplicatedStorage")
local db = false
local event = repliStorage.Shoot

mouse.Button1Down:Connect(function()
	if db == false then
		db = true
		local target = mouse.Hit.Position
		local tx = target.X
		local ty = target.Y
		local tz = target.Z
		
		local sp = tip.Position
		local spx = sp.X
		local spy = sp.Y
		local spz = sp.Z
			
		spx = math.floor(spx*100)/100
		spy = math.floor(spy*100)/100
		spz = math.floor(spz*100)/100
		tx = math.floor(tx*100)/100
		ty = math.floor(ty*100)/100
		tz = math.floor(tz*100)/100

		print(spx, spy, spz, "|", tx, ty, tz)
		
		event:FireServer(target, sp, handle, tip)
		
		wait(0.25)
		db = false
	end
end)

Assuming tip is the bullet origin, you should first choose the time it should take to get to the destination. Once you have this you should calculate the speed with the distance and time. Take the speed and make a vector in the direction of the bullet with the magnitude of the speed. Like this:

local shootTime = 5 -- I suck at naming variables lol
local distance = (sp-target).Magnitude
local speed = distance/shootTime
local velocityVector = (target-sp).Unit*speed -- gets the vector from sp -> target direction and sets the magnitude to the speed

Instead of a time, is it possible to do studs per second or something similar?

You said you wanted the speed to be different based on the distance. If you want a constant speed just set the speed variable and remove the first two lines.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.