How would i add a "max" to mouse position?

so i’ve been trying to make a item where you can throw. The only thing bad about this is it doesn’t really have a cap speed of how fast or far it can go. I know this most likely has something to do with ray casting, but I’m not good at ray casting and I have no idea how I would set this up. Since its using mouse position, the higher the number is, the further and faster it goes leaving no actual limit for it

Local script:

local players = game:GetService("Players")
local player = players.LocalPlayer
local mouse = player:GetMouse()

local tool = script.Parent
local remote = tool:WaitForChild("RemoteEvent")

remote.OnClientEvent:Connect(function()
	remote:FireServer(mouse.Hit.Position)
end)

script:


local players = game:GetService("Players")
local tool = script.Parent
local handle = tool.Handle
local remote = tool.RemoteEvent

tool.Activated:Connect(function()
	if not tool.Enabled then return end
	tool.Enabled = false
	
	local character = tool.Parent
	local player = players:GetPlayerFromCharacter(character)
	if player then
		remote:FireClient(player)
	end
end)

remote.OnServerEvent:Connect(function(player, mousePosition)
	local direction = (mousePosition - handle.Position)
	local force = direction * 2 + Vector3.new(0, workspace.Gravity / 4, 0)
	handle.AssemblyLinearVelocity = force
	tool.Parent = workspace
end)

Thanks in advance!

remote.OnServerEvent:Connect(function(player, mousePosition)
	local direction = mousePosition - handle.Position
	local distance = math.min(direction.Magnitude, maxForce) -- Set Max force
	local force = direction.Unit * distance * 2 + Vector3.new(0, workspace.Gravity / 4, 0)
	handle.AssemblyLinearVelocity = force
	tool.Parent = workspace
end)
2 Likes
  1. you can only use numbers for math class functions.
  2. math.clamp(force) wont work because force is a vector
  3. using math.min is better (only in some cases).
1 Like

Thanks, I really want to learn from this so can I ask a few questions?

1: how does the magnitude effect this?
2: what is direction.Unit?

  1. the magnitude is a property of Vector3. Its basically the distance of the Vector.
    example: Vector3.new(0,5,0) → 5
    by limitng the magnitude, you limit the “force”

  2. Unit is also a property of Vector3. This one is a Vector3 but with a max distance of 1.
    example: Vector3.new(3,0,0).Unit → Vector3.new(1,0,0)

so basically, we can multiply the vector unit by its distance, to extend it.
example Vector3.new(3,0,0)
distance: 3
unit: Vector3.new(1,0,0)
distance * unit = Vector3.new(1*3,0,0)

1 Like

alright, thanks a lot for this!