Certainly! Below is a Roblox script that accomplishes your requirements:
- Smoothly moves the player's head orientation based on the camera's position.
- Replicates the head movement to all players using a
RemoteEvent.
- Implements a maximum rotation limit to prevent exaggerated movements.
- Optimizes server load by only sending updates when significant camera changes are detected.
Overview
We'll split the script into two parts:
- LocalScript: Runs on the client, detects camera movement, and sends head rotation updates to the server when significant changes occur.
- Server Script: Receives updates from clients and broadcasts them to all other clients to replicate the head movement.
1. Setup
First, insert a RemoteEvent into ReplicatedStorage. We'll use this to communicate between the client and server.
-- In ReplicatedStorage
-- Add a RemoteEvent named "HeadRotationEvent"
2. LocalScript (Client-Side)
Place this LocalScript inside StarterPlayerScripts or StarterCharacterScripts.
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local headRotationEvent = ReplicatedStorage:WaitForChild("HeadRotationEvent")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
-- Configuration
local ROTATION_THRESHOLD = 2 -- Degrees
local MAX_ROTATION_ANGLE = 45 -- Degrees
-- Store the last sent rotation
local lastSentRotation = nil
-- Function to calculate the rotation difference
local function rotationDifference(r1, r2)
local delta = math.abs(r1 - r2)
if delta > 180 then
delta = 360 - delta
end
return delta
end
-- Monitor camera changes
RunService.RenderStepped:Connect(function()
local cameraCFrame = workspace.CurrentCamera.CFrame
local cameraLookVector = cameraCFrame.LookVector
-- Get the head's position
local headPosition = head.Position
-- Calculate the direction from the head to the camera
local direction = (cameraCFrame.Position - headPosition).Unit
-- Calculate the horizontal and vertical angles
local horizontalAngle = math.deg(math.atan2(direction.X, direction.Z))
local verticalAngle = math.deg(math.asin(direction.Y))
-- Clamp the angles to the maximum rotation angle
horizontalAngle = math.clamp(horizontalAngle, -MAX_ROTATION_ANGLE, MAX_ROTATION_ANGLE)
verticalAngle = math.clamp(verticalAngle, -MAX_ROTATION_ANGLE, MAX_ROTATION_ANGLE)
-- Round the angles to reduce unnecessary updates
horizontalAngle = math.floor(horizontalAngle * 100) / 100
verticalAngle = math.floor(verticalAngle * 100) / 100
-- Create a CFrame for the head rotation
local headRotation = CFrame.Angles(math.rad(-verticalAngle), math.rad(horizontalAngle), 0)
-- Check if the rotation has changed significantly
local significantChange = false
if lastSentRotation then
local x1, y1, z1 = lastSentRotation:ToOrientation()
local x2, y2, z2 = headRotation:ToOrientation()
local diffX = rotationDifference(math.deg(x1), math.deg(x2))
local diffY = rotationDifference(math.deg(y1), math.deg(y2))
if diffX >= ROTATION_THRESHOLD or diffY >= ROTATION_THRESHOLD then
significantChange = true
end
else
significantChange = true
end
if significantChange then
-- Send the rotation to the server
headRotationEvent:FireServer(headRotation)
lastSentRotation = headRotation
end
end)
3. Server Script (Server-Side)
Place this Script inside ServerScriptService.
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local headRotationEvent = ReplicatedStorage:WaitForChild("HeadRotationEvent")
-- Table to keep track of player characters
local playerCharacters = {}
-- When a player joins, keep track of their character
Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
playerCharacters[player] = character
end)
end)
-- When a player leaves, remove them from the table
Players.PlayerRemoving:Connect(function(player)
playerCharacters[player] = nil
end)
-- Function to broadcast head rotation to other clients
local function onHeadRotationReceived(player, headRotation)
-- Validate the headRotation is a CFrame
if typeof(headRotation) ~= "CFrame" then
return
end
-- Broadcast to all clients except the sender
headRotationEvent:FireAllClients(player, headRotation)
end
-- Connect the event
headRotationEvent.OnServerEvent:Connect(onHeadRotationReceived)
4. LocalScript for Updating Other Players (Client-Side)
Now, we need a script to listen for head rotation updates from other players and apply them. Place this LocalScript inside StarterPlayerScripts or StarterCharacterScripts.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local headRotationEvent = ReplicatedStorage:WaitForChild("HeadRotationEvent")
-- Table to keep track of other players' heads
local playerHeads = {}
-- Function to apply head rotation
local function onHeadRotationReceived(senderPlayer, headRotation)
if senderPlayer == Players.LocalPlayer then
return -- Ignore our own updates
end
local character = senderPlayer.Character
if character then
local head = character:FindFirstChild("Head")
if head and head:IsA("BasePart") then
-- Apply the rotation smoothly
if not playerHeads[senderPlayer] then
playerHeads[senderPlayer] = head
end
-- Use TweenService for smooth rotation
local TweenService = game:GetService("TweenService")
local tweenInfo = TweenInfo.new(0.1, Enum.EasingStyle.Linear)
local goal = {}
goal.CFrame = head.CFrame.Position + headRotation
local tween = TweenService:Create(head, tweenInfo, goal)
tween:Play()
end
end
end
-- Listen for updates from the server
headRotationEvent.OnClientEvent:Connect(onHeadRotationReceived)
Explanation
Optimizations
-
Reduced Server Load
- By only sending updates when significant camera movements are detected, we reduce the frequency of remote events.
- Rounding rotation angles helps prevent minimal changes from triggering updates.
-
Efficient Communication
- The server relays the minimum necessary data (the head rotation
CFrame) to other clients.
- Clients perform the necessary calculations to apply the rotation smoothly.
Notes
-
Security Considerations
- Always validate client data on the server to prevent exploiters from sending malicious data.
- In this script, we check that the received
headRotation is indeed a CFrame.
-
Customization
- You can adjust
ROTATION_THRESHOLD and MAX_ROTATION_ANGLE in the client script to fine-tune the sensitivity and rotation limits.
-
Testing
- Test with multiple players to ensure the head rotations are replicating correctly.
- Observe performance to ensure that the optimizations effectively reduce unnecessary updates.
Feel free to ask if you have any questions or need further assistance with this script!