Raycast distance and changing damage based off that

Im making an fps game, i’m trying to make it like PF or Arsenal, in those games, the further away you are from the target, the less damage it will do, i know how to measure the distance

Calculating Distance Variable:

	local Distance = (BarrelPos - MousePos).magnitude

but i can’t think of the maths that i’d need to do to calculate what damage the player should do at the set range.

RayCast Code:

local function Raycast(player,BarrelPos,MousePos)
	local ray = workspace:Raycast(BarrelPos,(MousePos - BarrelPos).unit * 5000,RayCastParam) 
	local Distance = (BarrelPos - MousePos).magnitude
	if ray then
		local humanoid = ray.Instance.Parent:FindFirstChild("Humanoid")
		local Enemy = game.Players:GetPlayerFromCharacter(ray.Instance.Parent)
		if CanShoot == true then
			if humanoid and not humanoid:IsDescendantOf(player.Character) then
				if ray.Instance.Name:lower() == "headhitbox" or ray.Instance.Name:lower() == "head" then
					HitMarkerSound:Play()
					HitMarkerImage.ImageTransparency = 0
					FireEvent:FireServer(humanoid,HeadShotDamage)
					print("headshot")
				elseif ray.Instance.Name:lower() == "bodyhitbox" or ray.Instance.Name:lower() ~= "head" then
					HitMarkerImage.ImageTransparency = 0
					HitMarkerSound:Play()
					FireEvent:FireServer(humanoid,Damage)
					print("body shot")
				end
			end
			if Enemy then
				
			end
		end
		end
end
1 Like

Put this in your code :

local Damage = Damage/Distance * Damage--put "local", it is important :)

i don’t speak english very well lol

Sometimes when im not even that far away from what im shooting, i get really low values, how do i increase that? i set the distance to

(BarrelPos - ray.hit.Instance).magnitude

you could increase the damage value or do this instead

local Damage = Distance/CriticDamageDistance * Damage

(not even sure if this would work lol)

the problem with this code is that it works the oppisite way, the further away you are, the more damage you do

my bad, it is CriticDamageDistance/Distance * Damage

2 Likes

also if you think it is op you could use math.min(number,max number)

local Damage = math.min(CriticDamageDistance/Distance,number) *Damage