Moving an object by equipping the tool and clicking

I made something similar to the system of giving tools when arriving at any region and receiving tools when leaving that area.

However, I still couldn’t quite achieve what I wanted. I am trying to develop a system similar to a very simple tennis system.

I added a ClickDetector to the Ball and it will move both horizontally and vertically in the direction the player is facing while on the ground.

If it is clicked while in the air, it will be thrown horizontally from a slightly lower height.
image

LocalScript (StarterPlayerScripts):

local ball = workspace:WaitForChild("Ball")
local racket = nil

player.CharacterAdded:Connect(function(character)
	character.ChildAdded:Connect(function(child)
		if child:IsA("Tool") and child.Name == "Racket" then
			racket = child
		end
	end)
end)

ball.ClickDetector.MouseClick:Connect(function()
	if racket then
		local remoteEvent = ReplicatedStorage:WaitForChild("RacketActivated")
		remoteEvent:FireServer()
	end
end)

Script (ServerScriptService):

local function onRacketActivated(player)
	local character = player.Character
	if not character then return end

	local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
	if not humanoidRootPart then return end

	local lookVector = humanoidRootPart.CFrame.LookVector

	local isOnGround = ball.Position.Y <= humanoidRootPart.Position.Y

	local direction
	if isOnGround then
		direction = Vector3.new(lookVector.X * groundHitForce.X, groundHitForce.Y, lookVector.Z * groundHitForce.Z)
	else
		direction = Vector3.new(lookVector.X * airHitForce.X, airHitForce.Y, lookVector.Z * airHitForce.Z)
	end

	local bodyVelocity = Instance.new("BodyVelocity")
	bodyVelocity.Velocity = direction
	bodyVelocity.MaxForce = Vector3.new(10000, 10000, 10000)
	bodyVelocity.Parent = ball

	Debris:AddItem(bodyVelocity, 0.5)
end

racketActivatedEvent.OnServerEvent:Connect(function(player)
	onRacketActivated(player)
end)

I’m still not sure what your problem is but you can try detecting the ground height and disabling the ability to click it when it is in the air.

Like this:

local Ball = workspace.YourBall
local GroundHeight = 1 -- Let's say 1 stud
while wait() do
    if not Ball.Position.Y > GroundHeight then 
        -- Insert code here
    end
end

Hope this helps! :+1: :happy1: