[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;
}
}
Yes, the code you've provided does send input to the server even when no keys are pressed. Specifically, it sends an action with the value "stop" at regular intervals (every movementUpdateRate seconds, which is set to 0.1 seconds by default). This is intended to keep the server updated about the player's current state, even when that state is "not moving."
Here's a detailed explanation:
Sending Input When No Keys Are Pressed
In your HandleMovementInput() method, the code determines the player's action based on the current key inputs:
csharp
private void HandleMovementInput()
{
// Determine action based on input
string action = "stop";
// ... get key inputs ...
// Decide action based on key presses
if (forward && !backward)
{
action = "forward";
}
// ... other directions ...
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;
}
}
When no keys are pressed, all the forward, backward, left, right, and jump variables are false, so action remains "stop". The code then checks if the movement state has changed or if the movement update interval has elapsed. Even if shouldUpdate is false, the condition Time.time - lastMovementUpdate >= movementUpdateRate will eventually be true, ensuring that the "stop" action is sent to the server periodically.
Why the Bot Is Constantly Moving
The constant movement you're observing is likely due to the way the player's position is synchronized with the server and not solely because of the input. Specifically, the SyncPositionWithServer() coroutine is updating the player's position based on data received from the server:
This coroutine continuously fetches the bot's position from the server and updates the player's position using Vector3.Lerp, which smoothly interpolates between the current position and the server's position. If the server is constantly sending new positions (perhaps due to its own updates or misinterpretation of the "stop" action), the client will constantly adjust its position toward these new coordinates, resulting in the constant movement you're seeing.
Potential Issues and Solutions
Server Handling of the "Stop" Action: The server might not be correctly handling the "stop" action and could be continuing to move the bot or sending position updates even when it should be stationary. Ensure that the server correctly interprets the "stop" action by halting any movement updates.
Position Synchronization Loop: If there's a discrepancy between the client's and server's positions due to network latency or update rates, a feedback loop can occur where the client and server continuously try to synchronize positions that are slightly off. This can cause jittery or constant movement.
Solution: Adjust the position synchronization logic to be less aggressive. For example, you might only update the client's position if the difference between the client and server positions exceeds a certain threshold. Additionally, consider using server authority for movement or implementing client-side prediction to smooth out the movement.
Input Noise: Ensure that there is no unintended input being registered. Sometimes, input devices might register slight movements even when at rest (e.g., analog sticks, or mouse drift). Since your code sends movement updates if there's any significant input change, ensure that the thresholds for input sensitivity are appropriate.
Debugging Tips:
Log Inputs: Add logs to output the input values being read to verify that no unintended inputs are being registered.
Log Server Responses: Output the server's position data to see if it's sending unexpected positions.
Check Update Rates: Ensure that the networkUpdateRate and movementUpdateRate are appropriate and not causing excessive updates.
Summary
Yes, the code sends input (with action "stop") even when no keys are pressed.
The constant movement is likely due to the position synchronization between the client and server.
Investigate the server's handling of actions and position updates to ensure it correctly processes the "stop" action and doesn't send unnecessary position updates.
Review the position synchronization logic to prevent continuous adjustments that cause movement when the bot should be stationary.
By addressing these areas, you should be able to resolve the issue of the bot constantly moving when no input is provided.