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;
}
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}");
}
}
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();
});
Certainly! I've updated your Unity FirstPersonController script to include predictive movement. The idea is to have the player move locally based on input while synchronizing with the server to correct any discrepancies. Here's the modified code with predictive movement added:
using System.Text;
using UnityEngine.Networking;
using UnityEngine;
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; // Added gravity
[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
[SerializeField] private float positionThreshold = 0.5f; // Threshold for position correction
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 CharacterController characterController;
private Vector3 moveDirection = Vector3.zero;
private float verticalVelocity = 0f;
private void Start()
{
playerCamera = GetComponentInChildren<Camera>();
if (playerCamera == null)
{
Debug.LogError("No camera found in children of FirstPersonController!");
enabled = false;
return;
}
characterController = GetComponent<CharacterController>();
if (characterController == null)
{
// Automatically add a CharacterController if not present
characterController = gameObject.AddComponent<CharacterController>();
}
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
// Start position sync coroutine
StartCoroutine(SyncPositionWithServer());
}
private void Update()
{
HandleMouseLook();
HandleMovementInput();
ApplyMovement(); // Apply local movement based on input
// 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
{
action = "stop";
}
// Movement vector
moveDirection = (transform.forward * (forward ? 1 : (backward ? -1 : 0)) +
transform.right * (right ? 1 : (left ? -1 : 0))).normalized;
// Adjust speed for sprinting
float speed = moveSpeed;
if (sprint)
{
speed *= sprintMultiplier;
}
moveDirection *= speed;
// Apply gravity
if (characterController.isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
if (jump)
{
verticalVelocity = jumpForce;
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
moveDirection.y = verticalVelocity;
// 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 ApplyMovement()
{
// Move the character controller
characterController.Move(moveDirection * Time.deltaTime);
}
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);
// Correct position if the difference exceeds the threshold
float distance = Vector3.Distance(transform.position, serverPosition);
if (distance > positionThreshold)
{
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;
}
}
Explanation of Changes:
Local Movement Simulation:
CharacterController: Added a CharacterController component for physics-based movement.
Gravity and Jumping: Implemented gravity and jumping physics with verticalVelocity and applied it to moveDirection.
ApplyMovement Method: Created a new ApplyMovement() method to move the player locally based on input.
Predictive Movement:
Local Input Handling: The player now moves locally without waiting for server confirmation.
Position Correction: In the SyncPositionWithServer() coroutine, we check if the distance between the local position and the server position exceeds a certain threshold (positionThreshold). If it does, we smoothly interpolate the player's position towards the server position to correct any drift.
Reduced Position Updates:
Threshold Adjustment: Only correcting the position when necessary reduces unnecessary corrections and makes the movement feel smoother.
Movement Input Refactoring:
Combined Move Direction: Calculated the moveDirection vector based on input keys for forward, backward, left, and right.
Sprint Speed Adjustment: Applied sprintMultiplier when sprinting.
Normalized Direction: Ensured the movement direction is normalized to prevent faster diagonal movement.
Gravity Application:
Vertical Movement: Added verticalVelocity to moveDirection.y to apply gravity and handle jumping.
How Predictive Movement Works:
Client-Side Prediction: The player's movement is calculated and applied locally without waiting for the server's response, allowing for immediate and responsive controls.
Server Synchronization: The client continuously sends movement and position data to the server.
Position Correction: The client periodically receives the server's position data. If there's a significant difference (e.g., due to lag or desynchronization), the client smoothly adjusts the player's position toward the server's position to maintain accuracy.
This approach improves the player's experience by reducing perceived latency and making controls feel more responsive, even when there's network delay.
Feel free to integrate this updated script into your project. Let me know if you need further assistance or adjustments!