I want to script something like this but dont have the right idea on how to do it

I want to create a script whereas the player has an int value inside their player, then there is a part inserted into workspace, and more you move towards that part, the number value of the players int value increases by a assigned number at an assigned rate, i already have the part and the int value but i dont really know how i would start to script a code where the players int value increases each time it moves towards the part

does anyone know how to do this?

1 Like

This should work fine
You only need to change a few variables that have a comment next to it

local Players = game.Players

local targetInstance    = workspace.Part -- Your part to grab the distance from
local distanceRate      = 1.5 			  -- The rate of the distance to change
local nearestDistance   = 100             -- The max "Distance" when the player is almost next to the part

function isPlayerMoving(humanoid)
	return humanoid.MoveDirection.X > 0 or humanoid.MoveDirection.X < 0 or humanoid.MoveDirection.Z > 0 or humanoid.MoveDirection.Z < 0 or humanoid.MoveDirection.Y > 0 or humanoid.MoveDirection.Y < 0
end

Players.PlayerAdded:Connect(function(player: Player) 
	local targetDistanceVal = Instance.new("IntValue",player)
	targetDistanceVal.Name = "Distance" -- Rename this to whatever you like
	player.CharacterAppearanceLoaded:Wait()
	
	local heartbeatSignal = nil
	
	player.Character.Humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(function()
		if isPlayerMoving(player.Character.Humanoid) and not heartbeatSignal then
			
			heartbeatSignal = game["Run Service"].Heartbeat:Connect(function(deltaTime: number) 
				
				local distance = (player.Character.HumanoidRootPart.Position - targetInstance.Position).Magnitude
				
				targetDistanceVal.Value = (nearestDistance - distance) * distanceRate
			end)
			
		elseif not isPlayerMoving(player.Character.Humanoid) then
			heartbeatSignal:Disconnect()
			heartbeatSignal = nil
		
		end

	end)

end)

3 Likes

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