add predictive movement and smoothen the movement code. dont make movement use a rigidbody or client-side, i still want it to be forwarded from the server
using System.Text;
using UnityEngine.Networking;
using UnityEngine;
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Text;
using System.Collections.Generic;
// 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();
if (playerCamera == null)
{
Debug.LogError("No camera found in children of FirstPersonController!");
enabled = false;
return;
}
// Send position updates to server periodically
if (Time.time - lastNetworkUpdate >= networkUpdateRate)
{
SendPositionToServer();
lastNetworkUpdate = Time.time;
}
}
// Send look direction to server if significant movement
if (Mathf.Abs(mouseX) > 0.01f || Mathf.Abs(mouseY) > 0.01f)
{
SendLookDirectionToServer();
}
}
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");
app.get('/bot/coordinates', (req, res) => {
if (bot && bot.entity) {
const position = bot.entity.position;
res.json({
x: position.x,
y: position.y,
z: position.z
});
} else {
res.status(404).json({
success: false,
error: 'Bot is not available'
});
}
});
app.post('/bot/coordinates', (req, res) => {
const { x, y, z } = req.body;
if (bot) {
// Perhaps store or log the coordinates, but do not change control states
res.json({
success: true,
message: Received coordinates x,{y}, ${z}
});
} else {
// Handle bot not available
}
});
app.post('/bot/look', (req, res) => {
const { x, y, z } = req.body;
if (bot) {
try {
const targetPosition = new Vec3(x, y, z);
bot.lookAt(targetPosition, true, () => {
res.json({
success: true,
message: Bot looking at x,{y}, ${z}
});
});
} catch (err) {
res.status(500).json({
success: false,
error: err.message
});
}
} else {
res.status(404).json({
success: false,
error: 'Bot is not available'
});
}
});
// New stop endpoint to clear any movement states
app.post('/bot/stop', (req, res) => {
if (bot) {
bot.clearControlStates();
res.json({
success: true,
message: 'Bot stopped'
});
} else {
res.status(404).json({
success: false,
error: 'Bot is not available'
});
}
});
app.listen(port, () => {
console.log(Server listening on port ${port});
initializeBot();
});
To improve the smoothness of the movement and add predictive movement without making it client-side or using a Rigidbody, we can implement interpolation between the positions received from the server. This means we'll smoothly transition the player's position from the last known server position to the new one over time.
Here's how you can modify your FirstPersonController script to achieve this:
Store Previous and Current Server Positions with Timestamps:
We need to keep track of the last two positions received from the server and the times we received them. This allows us to interpolate the player's position over the time between updates.
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;
// Initialize position variables
prevServerPosition = transform.position;
serverPosition = transform.position;
prevServerTime = Time.time;
serverTime = Time.time;
currentLerpTime = 0f;
// Start position sync coroutine
StartCoroutine(SyncPositionWithServer());
}
Modify SyncPositionWithServer to Update Positions and Times:
In the coroutine that syncs with the server, store the previous position and time before updating to the new server position.
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);
// Store previous server position and time
prevServerPosition = serverPosition;
prevServerTime = serverTime;
// Update current server position and time
serverPosition = new Vector3(coords.x, coords.y, coords.z);
serverTime = Time.time;
currentLerpTime = 0f;
}
else
{
Debug.LogWarning($"Position sync failed: {request.error}");
}
}
yield return new WaitForSeconds(networkUpdateRate);
}
}
Interpolate Position in Update:
In the Update method, increment currentLerpTime by Time.deltaTime and interpolate the player's position smoothly between the previous and current server positions based on the time since the last update.
private void Update()
{
HandleMouseLook();
HandleMovementInput();
// Send position updates to server periodically
if (Time.time - lastNetworkUpdate >= networkUpdateRate)
{
SendPositionToServer();
lastNetworkUpdate = Time.time;
}
// Interpolate position
currentLerpTime += Time.deltaTime;
float timeSinceLastUpdate = Time.time - prevServerTime;
float lerpDuration = serverTime - prevServerTime;
// Avoid division by zero
if (lerpDuration > 0f)
{
float t = currentLerpTime / lerpDuration;
t = Mathf.Clamp01(t);
transform.position = Vector3.Lerp(prevServerPosition, serverPosition, t);
}
else
{
transform.position = serverPosition;
}
}
Optional - Smooth Rotation (If Needed):
If you notice any jitter in rotation, you can apply a similar interpolation to the rotation based on the server's look direction.
Note: In this setup, rotation is client-side since the player controls the camera directly, and the look direction is sent to the server.
Ensure Consistent Network Update Rates:
To make interpolation effective, ensure that the networkUpdateRate is consistent and matches the server's update rate as closely as possible.
Updated FirstPersonController Script:
Here's the modified script incorporating the changes:
using System.Text;
using UnityEngine.Networking;
using UnityEngine;
using System.Collections;
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;
[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;
private string lastAction = "stop";
private bool lastJump = false;
private bool lastSprint = false;
private Vector3 prevServerPosition;
private float prevServerTime;
private float serverTime;
private float currentLerpTime;
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;
// Initialize position variables
prevServerPosition = transform.position;
serverPosition = transform.position;
prevServerTime = Time.time;
serverTime = Time.time;
currentLerpTime = 0f;
// 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;
}
// Interpolate position
currentLerpTime += Time.deltaTime;
float timeSinceLastUpdate = Time.time - prevServerTime;
float lerpDuration = serverTime - prevServerTime;
// Avoid division by zero
if (lerpDuration > 0f)
{
float t = currentLerpTime / lerpDuration;
t = Mathf.Clamp01(t);
transform.position = Vector3.Lerp(prevServerPosition, serverPosition, t);
}
else
{
transform.position = serverPosition;
}
}
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);
// Store previous server position and time
prevServerPosition = serverPosition;
prevServerTime = serverTime;
// Update current server position and time
serverPosition = new Vector3(coords.x, coords.y, coords.z);
serverTime = Time.time;
currentLerpTime = 0f;
}
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;
}
}
Explanation:
Interpolation:
By interpolating between the last two positions received from the server, we create a smooth transition between them.
currentLerpTime keeps track of how much time has passed since the last position update.
We calculate t as the ratio of currentLerpTime to the duration between server updates (lerpDuration).
transform.position is updated using Vector3.Lerp, providing smooth movement.
Avoiding Client-Side Prediction:
This approach does not predict future positions based on client input.
Movement is still entirely based on positions received from the server.
We simply interpolate between known positions to smooth out the movement.
Handling Variable Network Latency:
By using the actual time between server updates (serverTime - prevServerTime), the interpolation adapts to network conditions.
If there's a delay in receiving updates, the interpolation will pause at the last known position until a new one is received.
Benefits:
Smooth Movement:
Players will experience smoother movements as their position transitions gradually between updates.
No Client-Side Authority:
Since all positions are still based on server data, you maintain server authority over player movement.
Simple Implementation:
This method doesn't require complex networking or prediction algorithms.
Note:
Ensure that both the client and server maintain consistent update rates.
If the server sends positions less frequently, consider adjusting networkUpdateRate to match.
Test the implementation under various network conditions to fine-tune the interpolation.
Let me know if you need further assistance or adjustments to this approach!