Somethings wrong with my scripts

Hey so i made those scirpt what it does when you hold a keybind it makes the part follow players mouse and so it works but theres one glitch i dont understand how to fix so basicaly if im holding the keybind and i do not move my mouse the part by itself goes into the camera ill show a video of how it looks down but here are my scripts

-- LocalScript placed in StarterPlayerScripts or StarterCharacterScripts

local remoteEvent = script.Parent:WaitForChild("RemoteEvent")
local UIS = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()

local isHolding = false
local lastMousePosition = mouse.Hit.p -- Store the last known mouse position
local cooldown = 0.1 -- Cooldown between updates
local fixedDistance = 10 -- Fixed distance to maintain in front of the player

-- Function to send mouse position while holding the key
local function updatePartPosition()
	while isHolding do
		-- Check if the mouse has moved
		if (lastMousePosition - mouse.Hit.p).Magnitude > 0.1 then
			lastMousePosition = mouse.Hit.p -- Update last mouse position
			remoteEvent:FireServer("UpdatePosition", lastMousePosition)
		else
			-- If the mouse hasn't moved, keep the part at a fixed distance
			local character = player.Character
			if character and character:FindFirstChild("HumanoidRootPart") then
				local rootPart = character.HumanoidRootPart
				local fixedPosition = rootPart.Position + (rootPart.CFrame.LookVector * fixedDistance)
				remoteEvent:FireServer("UpdatePosition", fixedPosition)
			end
		end
		wait(cooldown) -- Cooldown between each update
	end
end

-- Handle when the key is pressed
local function onInputBegan(input)
	if input.KeyCode == Enum.KeyCode.Q and not isHolding then
		isHolding = true
		remoteEvent:FireServer("Pressed", mouse.Hit.p) -- Fire initial event

		-- Start updating the part's position
		updatePartPosition()
	end
end

-- Handle when the key is released
local function onInputEnded(input)
	if input.KeyCode == Enum.KeyCode.Q and isHolding then
		isHolding = false
		remoteEvent:FireServer("Released", mouse.Hit.p) -- Fire event for when key is released
	end
end

-- Connect input events to the functions
UIS.InputBegan:Connect(onInputBegan)
UIS.InputEnded:Connect(onInputEnded)

-- ServerScript that handles the RemoteEvent fired from the LocalScript

-- Get the RemoteEvent from the script's parent
local remoteEvent = script.Parent:WaitForChild("RemoteEvent")
local TweenService = game:GetService("TweenService")
local Workspace = game:GetService("Workspace") -- Workspace variable

-- Define the maximum distance the part can follow
local MAX_DISTANCE = 50 -- Max distance in studs

-- Function to limit the part's movement based on distance
local function limitDistance(player, targetPosition)
	-- Get the player's character and HumanoidRootPart
	local character = player.Character
	if not character or not character:FindFirstChild("HumanoidRootPart") then return targetPosition end

	local rootPart = character.HumanoidRootPart
	local playerPosition = rootPart.Position

	-- Calculate the distance between the player and the target position
	local distance = (targetPosition - playerPosition).Magnitude

	-- If the distance exceeds the max distance, clamp the position
	if distance > MAX_DISTANCE then
		-- Direction vector from player to target
		local direction = (targetPosition - playerPosition).Unit

		-- Clamp the position within the max distance
		return playerPosition + direction * MAX_DISTANCE
	end

	return targetPosition
end

-- Function to move the part to the (clamped) target position
local function movePartToPosition(part, player, targetPosition)
	-- Limit the target position based on distance
	local clampedPosition = limitDistance(player, targetPosition)

	-- Create a Tween to move the part smoothly to the clamped position
	local tweenInfo = TweenInfo.new(0.1, Enum.EasingStyle.Linear, Enum.EasingDirection.Out)
	local tween = TweenService:Create(part, tweenInfo, {Position = clampedPosition})
	tween:Play()
end

-- RemoteEvent listener to start moving the part when the event is fired
remoteEvent.OnServerEvent:Connect(function(player, action, mousePosition)
	local part = Workspace:FindFirstChild("FollowPart") -- The part to follow the mouse
	if part and mousePosition then
		if action == "Pressed" or action == "UpdatePosition" then
			-- Move the part to the (clamped) mouse position
			movePartToPosition(part, player, mousePosition)
		elseif action == "Released" then
			-- Optionally, handle logic for when the key is released
		end
	end
end)

and heres the video

1 Like

I don’t necessary know how to explain what is happening.

When using Mouse.Hit, the side of the part is detected as a hit, so the new position of the part will be the new hit position. You’ll do this again and again so the part will get closer.

You need to somehow blacklist the part from the hit detection. The following code should work as expected:

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
mouse.TargetFilter = part -- Your part goes there

However, you should read this article about raycasts which is a more powerful alternative to Mouse.Hit.

the issue in in the updatepartposition you should use the cframe camera instead of the character and check if the mouse has moved also use Task Library

local function updatePartPosition()
    while isHolding do
        local character = player.Character
        if character and character:FindFirstChild("HumanoidRootPart") then
            local rootPart = character.HumanoidRootPart
            local camera = workspace.CurrentCamera
            
            local targetPosition = camera.CFrame.Position + (camera.CFrame.LookVector * fixedDistance)
            
            if (lastMousePosition - mouse.Hit.p).Magnitude > 0.1 then
                targetPosition = mouse.Hit.p
                lastMousePosition = targetPosition
            end
            
            remoteEvent:FireServer("UpdatePosition", targetPosition)
        end
        task.wait(cooldown)
    end
end

hey its still the same it didnt change anything

hey its the same it didnt change anything

You must use a Raycast, disable CanQuery for the part, and do not use Mouse.Hit

Because when you use Mouse.Hit, the position of the part is set directly to the position of your mouse cursor, but then the Mouse.Hit variable is recalculated since Mouse.Hit is now on the part, making the part get closer each time until it is no longer on the screen and the process repeats.

hey so i tried using raycast and heres the loclascirpt i made whats wrong with it – LocalScript placed in StarterPlayerScripts or StarterCharacterScripts sorry if my scirpts are bad or works badly im new to scripting

-- Get the RemoteEvent
local remoteEvent = script.Parent:WaitForChild("RemoteEvent")

-- Define variables
local UIS = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local cooldown = 0.1 -- cooldown time in seconds
local maxDistance = 50 -- Maximum distance for the part to follow the mouse
local isHolding = false

-- Disable CanQuery for the part (assumed to be accessible here)
local part = game.workspace:WaitForChild("FollowPart") -- Replace with the actual part name
part.CanQuery = false

-- Function to continuously update the part position
local function updatePartPosition()
	while isHolding do
		local character = player.Character
		if character and character:FindFirstChild("HumanoidRootPart") then
			local camera = workspace.CurrentCamera
			local rayOrigin = camera.CFrame.Position
			local rayDirection = camera.CFrame.LookVector * maxDistance

			-- Create a RaycastParams object
			local raycastParams = RaycastParams.new()
			raycastParams.FilterDescendantsInstances = {character} -- Ignore the player's character
			raycastParams.FilterType = Enum.RaycastFilterType.Whitelist -- Only hit the objects we want

			-- Perform the raycast
			local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)

			local targetPosition
			if raycastResult then
				targetPosition = raycastResult.Position -- Use the position of the hit
			else
				targetPosition = rayOrigin + rayDirection -- If nothing is hit, use the max distance position
			end

			-- Fire the updated target position to the server
			remoteEvent:FireServer("UpdatePosition", targetPosition)
		end
		task.wait(cooldown) -- Wait for cooldown duration before the next update
	end
end

-- Function to handle key input
local function onInputBegan(input)
	if input.KeyCode == Enum.KeyCode.Q then
		isHolding = true
		updatePartPosition() -- Call the update function when the key is pressed
	end
end

local function onInputEnded(input)
	if input.KeyCode == Enum.KeyCode.Q then
		isHolding = false
		remoteEvent:FireServer("Released")
	end
end

-- Connect functions to input events
UIS.InputBegan:Connect(onInputBegan)
UIS.InputEnded:Connect(onInputEnded) 

instead of Whitelist which is deprecated use include

This script should work:

-- Get the RemoteEvent

-- Define variables
local UIS = game:GetService("UserInputService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local player = Players.LocalPlayer

local mouse = player:GetMouse()

--local cooldown = 1 -- cooldown time in seconds
local maxDistance = 50 -- Maximum distance for the part to follow the mouse
local isHolding = false

-- Disable CanQuery for the part (assumed to be accessible here)
local part = game.workspace:WaitForChild("FollowPart") -- Replace with the actual part name
part.CanQuery = false
part.CanCollide = false

local function unitRay()
	local ur = mouse.UnitRay
	return ur.Origin, ur.Direction * 10000
end

-- Function to continuously update the part position
local function updatePartPosition()
	local loop
	loop = RunService.Heartbeat:Connect(function(dt)
		local character = player.Character
		if character and character:FindFirstChild("HumanoidRootPart") then


			local origin, direction = unitRay()
			local params = RaycastParams.new()

			params.FilterType = Enum.RaycastFilterType.Blacklist
			params.FilterDescendantsInstances = {character}

			local ray = workspace:Raycast(origin, direction, params)

			local targetPosition

			if ray then
				if ray.Position then
					targetPosition = ray.Position -- Use the position of the hit

					targetPosition = targetPosition + Vector3.new(0, part.Size.Y / 2, 0)
					
					local magnitude = (character:WaitForChild("HumanoidRootPart").Position - targetPosition).Magnitude
					
					if magnitude < maxDistance then
						part.Position = targetPosition
					end
					
				end
			end

		end
		--task.wait(cooldown) -- Wait for cooldown duration before the next update
		
		if isHolding == false then
			loop:Disconnect()
		end
	end)
end

-- Function to handle key input
local function onInputBegan(input)
	if input.KeyCode == Enum.KeyCode.Q then
		print("holding")
		isHolding = true
		spawn(updatePartPosition) -- Call the update function when the key is pressed
	end
end

local function onInputEnded(input)
	if input.KeyCode == Enum.KeyCode.Q then
		isHolding = false
	end
end

-- Connect functions to input events
UIS.InputBegan:Connect(onInputBegan)
UIS.InputEnded:Connect(onInputEnded)

same glitch but now part goes even faster to the players camera

can u use the new script i send? I edited it

i used it thank you so much the new script now works!!!

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