[Header("Mouse Look Settings")]
[SerializeField] private float mouseSensitivity = 2f;
[SerializeField] private float maxLookAngle = 80f;
[Header("Network Settings")]
[SerializeField] private string serverUrl = "http://localhost:8000";
[SerializeField] private float networkUpdateRate = 0.1f; // Seconds between position updates
[SerializeField] private float movementUpdateRate = 0.1f; // Seconds between movement updates
private Camera playerCamera;
private float verticalRotation = 0f;
private Vector3 serverPosition;
private float lastNetworkUpdate;
private float lastMovementUpdate;
// Removed controlStates dictionary as we now work with actions
private string lastAction = "stop";
private bool lastJump = false;
private bool lastSprint = false;
private void Start()
{
playerCamera = GetComponentInChildren<Camera>();
if (playerCamera == null)
{
Debug.LogError("No camera found in children of FirstPersonController!");
enabled = false;
return;
}
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
// Start position sync coroutine
StartCoroutine(SyncPositionWithServer());
}
private void Update()
{
HandleMouseLook();
HandleMovementInput();
// Send position updates to server periodically
if (Time.time - lastNetworkUpdate >= networkUpdateRate)
{
SendPositionToServer();
lastNetworkUpdate = Time.time;
}
}
private void HandleMouseLook()
{
// Horizontal rotation
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
transform.Rotate(Vector3.up * mouseX);
// Vertical rotation (camera only)
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
verticalRotation -= mouseY;
verticalRotation = Mathf.Clamp(verticalRotation, -maxLookAngle, maxLookAngle);
playerCamera.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
// Send look direction to server if significant movement
if (Mathf.Abs(mouseX) > 0.01f || Mathf.Abs(mouseY) > 0.01f)
{
SendLookDirectionToServer();
}
}
private void HandleMovementInput()
{
// Determine action based on input
string action = "stop";
bool jump = Input.GetKey(KeyCode.Space);
bool sprint = Input.GetKey(KeyCode.LeftShift);
bool forward = Input.GetKey(KeyCode.W);
bool backward = Input.GetKey(KeyCode.S);
bool left = Input.GetKey(KeyCode.A);
bool right = Input.GetKey(KeyCode.D);
// Decide action based on key presses
if (forward && !backward)
{
action = "forward";
}
else if (backward && !forward)
{
action = "backward";
}
else if (left && !right)
{
action = "left";
}
else if (right && !left)
{
action = "right";
}
else if (jump)
{
action = "jump";
}
else
{
action = "stop";
}
// Check if movement state has changed
bool shouldUpdate = action != lastAction || jump != lastJump || sprint != lastSprint;
// Only send movement update if something changed or update timer elapsed
if (shouldUpdate || Time.time - lastMovementUpdate >= movementUpdateRate)
{
SendMovementToServer(action, jump, sprint);
lastMovementUpdate = Time.time;
// Update last known states
lastAction = action;
lastJump = jump;
lastSprint = sprint;
}
}
private void SendMovementToServer(string action, bool jump, bool sprint)
{
StartCoroutine(PostMovementRequest(action, jump, sprint));
}
private void SendPositionToServer()
{
StartCoroutine(PostPositionRequest());
}
private IEnumerator PostPositionRequest()
{
var posData = new CoordinateData
{
x = transform.position.x,
y = transform.position.y,
z = transform.position.z
};
string json = JsonUtility.ToJson(posData);
using (UnityWebRequest request = new UnityWebRequest($"{serverUrl}/bot/coordinates", "POST"))
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
request.uploadHandler = new UploadHandlerRaw(jsonBytes);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning($"Position request failed: {request.error}");
}
}
}
private void SendLookDirectionToServer()
{
Vector3 lookTarget = playerCamera.transform.position + playerCamera.transform.forward * 100f;
StartCoroutine(PostLookRequest(lookTarget));
}
private IEnumerator SyncPositionWithServer()
{
while (enabled)
{
using (UnityWebRequest request = UnityWebRequest.Get($"{serverUrl}/bot/coordinates"))
{
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
string json = request.downloadHandler.text;
CoordinateData coords = JsonUtility.FromJson<CoordinateData>(json);
serverPosition = new Vector3(coords.x, coords.y, coords.z);
transform.position = Vector3.Lerp(transform.position, serverPosition, 0.5f);
}
else
{
Debug.LogWarning($"Position sync failed: {request.error}");
}
}
yield return new WaitForSeconds(networkUpdateRate);
}
}
private IEnumerator PostMovementRequest(string action, bool jump, bool sprint)
{
var moveData = new MovementData
{
action = action,
jump = jump,
sprint = sprint
};
string json = JsonUtility.ToJson(moveData);
using (UnityWebRequest request = new UnityWebRequest($"{serverUrl}/bot/move", "POST"))
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
request.uploadHandler = new UploadHandlerRaw(jsonBytes);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning($"Movement request failed: {request.error}");
}
}
}
private IEnumerator PostLookRequest(Vector3 lookTarget)
{
var lookData = new CoordinateData
{
x = lookTarget.x,
y = lookTarget.y,
z = lookTarget.z
};
string json = JsonUtility.ToJson(lookData);
using (UnityWebRequest request = new UnityWebRequest($"{serverUrl}/bot/look", "POST"))
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
request.uploadHandler = new UploadHandlerRaw(jsonBytes);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning($"Look request failed: {request.error}");
}
}
}
[System.Serializable]
private class MovementData
{
public string action;
public bool jump;
public bool sprint;
}
[System.Serializable]
private class CoordinateData
{
public float x;
public float y;
public float z;
}
}
Certainly! The movement appears choppy because the player's position is primarily being updated based on the server's response in the SyncPositionWithServer coroutine. This method only updates the position at intervals defined by networkUpdateRate, causing infrequent updates that result in stuttering or choppy movement.
To make the movement smoother, you should implement client-side movement prediction. This means handling the player's movement locally in the Update or FixedUpdate methods, allowing for immediate response to input, while still synchronizing with the server periodically to correct any discrepancies.
Here's how you can modify your script to achieve smoother movement:
Implement Local Movement: Use Unity's CharacterController or manipulate the player's transform to move the player locally based on input.
Periodic Server Synchronization: Continue syncing with the server to correct any differences between the client's position and the server's authoritative state.
Interpolate Movement Smoothly: When adjusting the player's position based on the server's response, interpolate smoothly to avoid sudden jumps.
Below is the modified script with these changes applied:
csharp
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Text;
using System.Collections.Generic;
public class FirstPersonController : MonoBehaviour
{
[Header("Movement Settings")]
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float sprintMultiplier = 1.5f;
[SerializeField] private float jumpForce = 5f;
[SerializeField] private float gravity = 9.81f;
[Header("Mouse Look Settings")]
[SerializeField] private float mouseSensitivity = 2f;
[SerializeField] private float maxLookAngle = 80f;
[Header("Network Settings")]
[SerializeField] private string serverUrl = "http://localhost:8000";
[SerializeField] private float networkUpdateRate = 0.1f; // Seconds between position updates
private Camera playerCamera;
private CharacterController characterController;
private float verticalRotation = 0f;
private Vector3 moveDirection = Vector3.zero;
private Vector3 serverPosition;
private float lastNetworkUpdate;
private float verticalVelocity;
private bool isGrounded;
private void Start()
{
playerCamera = GetComponentInChildren<Camera>();
characterController = GetComponent<CharacterController>();
if (playerCamera == null)
{
Debug.LogError("No camera found in children of FirstPersonController!");
enabled = false;
return;
}
if (characterController == null)
{
Debug.LogError("No CharacterController component found on the player!");
enabled = false;
return;
}
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
// Start position sync coroutine
StartCoroutine(SyncPositionWithServer());
}
private void Update()
{
HandleMouseLook();
HandleMovementInput();
// Send position updates to server periodically
if (Time.time - lastNetworkUpdate >= networkUpdateRate)
{
SendPositionToServer();
lastNetworkUpdate = Time.time;
}
}
private void HandleMouseLook()
{
// Horizontal rotation
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
transform.Rotate(Vector3.up * mouseX);
// Vertical rotation (camera only)
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
verticalRotation -= mouseY;
verticalRotation = Mathf.Clamp(verticalRotation, -maxLookAngle, maxLookAngle);
playerCamera.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
// Send look direction to server if significant movement
if (Mathf.Abs(mouseX) > 0.01f || Mathf.Abs(mouseY) > 0.01f)
{
SendLookDirectionToServer();
}
}
private void HandleMovementInput()
{
isGrounded = characterController.isGrounded;
// Get input axes
float moveZ = Input.GetAxis("Vertical");
float moveX = Input.GetAxis("Horizontal");
// Determine movement direction
Vector3 forward = transform.forward;
Vector3 right = transform.right;
Vector3 desiredMoveDirection = (forward * moveZ + right * moveX).normalized;
// Apply movement speed
float speed = moveSpeed;
if (Input.GetKey(KeyCode.LeftShift))
{
speed *= sprintMultiplier;
}
// Apply gravity
if (isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
// Handle Jump
if (Input.GetKeyDown(KeyCode.Space))
{
verticalVelocity = jumpForce;
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
// Combine movement directions
moveDirection = desiredMoveDirection * speed;
moveDirection.y = verticalVelocity;
// Move the character controller
characterController.Move(moveDirection * Time.deltaTime);
// Send movement input to the server
SendMovementToServer(desiredMoveDirection, Input.GetKey(KeyCode.Space), Input.GetKey(KeyCode.LeftShift));
}
private void SendMovementToServer(Vector3 moveDirection, bool jump, bool sprint)
{
StartCoroutine(PostMovementRequest(moveDirection, jump, sprint));
}
private void SendPositionToServer()
{
StartCoroutine(PostPositionRequest());
}
private IEnumerator PostPositionRequest()
{
var posData = new CoordinateData
{
x = transform.position.x,
y = transform.position.y,
z = transform.position.z
};
string json = JsonUtility.ToJson(posData);
using (UnityWebRequest request = new UnityWebRequest($"{serverUrl}/bot/coordinates", "POST"))
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
request.uploadHandler = new UploadHandlerRaw(jsonBytes);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning($"Position request failed: {request.error}");
}
}
}
private void SendLookDirectionToServer()
{
Vector3 lookDirection = playerCamera.transform.forward;
StartCoroutine(PostLookRequest(lookDirection));
}
private IEnumerator SyncPositionWithServer()
{
while (enabled)
{
using (UnityWebRequest request = UnityWebRequest.Get($"{serverUrl}/bot/coordinates"))
{
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
string json = request.downloadHandler.text;
CoordinateData coords = JsonUtility.FromJson<CoordinateData>(json);
serverPosition = new Vector3(coords.x, coords.y, coords.z);
// Smoothly interpolate to the server position
transform.position = Vector3.Lerp(transform.position, serverPosition, Time.deltaTime * 5f);
}
else
{
Debug.LogWarning($"Position sync failed: {request.error}");
}
}
yield return new WaitForSeconds(networkUpdateRate);
}
}
private IEnumerator PostMovementRequest(Vector3 moveDirection, bool jump, bool sprint)
{
var moveData = new MovementData
{
moveX = moveDirection.x,
moveY = moveDirection.y,
moveZ = moveDirection.z,
jump = jump,
sprint = sprint
};
string json = JsonUtility.ToJson(moveData);
using (UnityWebRequest request = new UnityWebRequest($"{serverUrl}/bot/move", "POST"))
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
request.uploadHandler = new UploadHandlerRaw(jsonBytes);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning($"Movement request failed: {request.error}");
}
}
}
private IEnumerator PostLookRequest(Vector3 lookDirection)
{
var lookData = new DirectionData
{
x = lookDirection.x,
y = lookDirection.y,
z = lookDirection.z
};
string json = JsonUtility.ToJson(lookData);
using (UnityWebRequest request = new UnityWebRequest($"{serverUrl}/bot/look", "POST"))
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
request.uploadHandler = new UploadHandlerRaw(jsonBytes);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning($"Look request failed: {request.error}");
}
}
}
[System.Serializable]
private class MovementData
{
public float moveX;
public float moveY;
public float moveZ;
public bool jump;
public bool sprint;
}
[System.Serializable]
private class CoordinateData
{
public float x;
public float y;
public float z;
}
[System.Serializable]
private class DirectionData
{
public float x;
public float y;
public float z;
}
}
Explanation of Changes:
Local Movement Handling:
CharacterController: Added a CharacterController component to handle physics and collisions.
Movement Input: The HandleMovementInput method now processes movement input and moves the player immediately.
Gravity and Jumping: Applied gravity and handled jumping locally.
Smooth Position Synchronization:
In the SyncPositionWithServer coroutine, adjusted the interpolation factor to use Time.deltaTime * smoothingSpeed for smoother adjustments.
Set a smoothingSpeed (e.g., 5f) to control how quickly the player moves toward the server position.
Movement Data Serialization:
Modified the MovementData class to send raw movement input (moveX, moveY, moveZ) rather than action strings.
Updated the PostMovementRequest method accordingly.
Look Direction Serialization:
Created a DirectionData class to send the look direction as a vector.
Additional Recommendations:
Network Latency Compensation: Implement client-side prediction and server reconciliation to handle network latency effectively.
Input Smoothing: Apply smoothing algorithms if necessary to handle abrupt input changes.
Server Authority: Decide how authoritative the server should be. If discrepancies are minimal, minor corrections can be made without affecting the player's experience.
Note:
Ensure that your server is updated to handle the new data structures (MovementData and DirectionData) and process raw movement vectors instead of action strings.
By handling movement locally, you provide immediate feedback to the player's input, resulting in smoother movement. Periodic synchronization with the server ensures that the client and server states remain consistent without impacting the player's experience noticeably.