How to clamp my projectiles range?

So i want my projectile to have a range and i thought of using math.clamp. Im not sure if its possible but if it isnt i could just use raycasts

local Player = game.Players.LocalPlayer
local Character = Player.CharacterAdded:Wait()

local Max = 25
local Min = 1

local Mouse = Player:GetMouse()

local function CreatePart()

	local Part = Instance.new("Part")
	Part.Anchored = false
	Part.CanCollide = false
	Part.Size = Vector3.new(1, 1, 1)
	Part.Parent = workspace
	Part.Position = Character.HumanoidRootPart.Position

	return Part
end


Mouse.Button1Down:Connect(function()
	
	local Part = CreatePart()
	
	local Force = (Mouse.Hit.Position - Character.HumanoidRootPart.Position)
	local Direction = Force + Vector3.new(0, workspace.Gravity / 2, 0)
	
	Part:ApplyImpulse(Direction * Part.AssemblyMass)
	
end)
3 Likes

Do you want to delete the part when it exceeds the range?

2 Likes

No i want the projectile to only give enough force to end up at the max range if my mouse is further than it.

2 Likes

That’ll require some math to get the correct force to get an expected distance

3 Likes

Well yeah, i tried to figure it out myself but I cant. Thats why im asking this on the devforum

2 Likes

just use math.Clamp() to clamp the force, and for the math just multiply workspace.Gravity by Force.Magnitude

2 Likes

You cant just clamp the force trust me i already tried, its a vector 3. If I have to use magnitude how would the calculations look that?

2 Likes
local YourVector = YourVector
local clamped = math.clamp(YourVector.Magnitude, Min, Max)
local result = YourVector.Unit * clamped

So it will be:

local Force = (Mouse.Hit.Position - Character.HumanoidRootPart.Position)
local Clamp = math.clamp(Force.Magnitude, Min, Max)
Force = Force.Unit * Clamp
local Direction = Force + Vector3.new(0, workspace.Gravity / 2, 0)
	
Part:ApplyImpulse(Direction * Part.AssemblyMass)
	
2 Likes

You can make something that shoots towards a point by following this tutorial:

A very easy approximate way to limit the range is just to cap the length of the vector:

local targetPosition -- Set to the position of the target (e.g. the mouse's 3D target)
local characterPosition -- Set to the position of the character

local targetDisplacement = targetPosition - characterPosition

local MAX_DISTANCE = 100
-- If the length of the `targetDisplacement` is too long, set the length to `MAX_DISTANCE`
if targetDisplacement > MAX_DISTANCE then
    targetDisplacement = targetDisplacement.Unit * MAX_DISTANCE
end

newTargetPosition = characterPosition + targetDisplacement
1 Like

Thanks alot this was helpful

30 letteeeeeeerrrrrs

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