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
}
});
} else {
res.status(404).json({
success: false,
error: 'Bot is 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 modified your code to use WebSockets instead of HTTP requests for movement and position synchronization between your Unity client and Node.js server. Below, you'll find the updated code for both the Unity FirstPersonController script and the Node.js server.
Note:
On the Unity side, I've used the NativeWebSocket library, which is an open-source WebSocket client for Unity that works across different platforms.
On the Node.js server, I've incorporated the ws library to handle WebSocket connections.
Unity: FirstPersonController.cs
Make sure to install the NativeWebSocket package in your Unity project. You can import it via the Unity Package Manager by adding it from GitHub.
csharp
using System.Text;
using UnityEngine;
using System.Collections.Generic;
using NativeWebSocket;
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 = "ws://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 WebSocket websocket;
private async 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;
// Initialize WebSocket connection
websocket = new WebSocket(serverUrl);
websocket.OnOpen += () =>
{
Debug.Log("Connected to server via WebSocket!");
};
websocket.OnError += (e) =>
{
Debug.LogError("WebSocket error: " + e);
};
websocket.OnClose += (e) =>
{
Debug.Log("WebSocket connection closed!");
};
websocket.OnMessage += (bytes) =>
{
string message = Encoding.UTF8.GetString(bytes);
HandleServerMessage(message);
};
// Connect to the server
await websocket.Connect();
}
private async void OnApplicationQuit()
{
if (websocket != null)
{
await websocket.Close();
}
}
private async void Update()
{
HandleMouseLook();
HandleMovementInput();
if (websocket.State == WebSocketState.Open)
{
// Send position updates to server periodically
if (Time.time - lastNetworkUpdate >= networkUpdateRate)
{
SendPositionToServer();
lastNetworkUpdate = Time.time;
}
#if !UNITY_WEBGL || UNITY_EDITOR
websocket.DispatchMessageQueue();
#endif
}
// 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 async void SendMovementToServer(string action, bool jump, bool sprint)
{
if (websocket.State == WebSocketState.Open)
{
var moveData = new MovementData
{
type = "movement",
action = action,
jump = jump,
sprint = sprint
};
string json = JsonUtility.ToJson(moveData);
await websocket.SendText(json);
}
}
private async void SendPositionToServer()
{
if (websocket.State == WebSocketState.Open)
{
var posData = new PositionData
{
type = "position",
x = transform.position.x,
y = transform.position.y,
z = transform.position.z
};
string json = JsonUtility.ToJson(posData);
await websocket.SendText(json);
}
}
private async void SendLookDirectionToServer()
{
if (websocket.State == WebSocketState.Open)
{
Vector3 lookTarget = playerCamera.transform.position + playerCamera.transform.forward * 100f;
var lookData = new LookData
{
type = "look",
x = lookTarget.x,
y = lookTarget.y,
z = lookTarget.z
};
string json = JsonUtility.ToJson(lookData);
await websocket.SendText(json);
}
}
private void HandleServerMessage(string message)
{
var baseMessage = JsonUtility.FromJson<BaseMessage>(message);
if (baseMessage != null)
{
if (baseMessage.type == "botPosition")
{
var botPosData = JsonUtility.FromJson<BotPositionData>(message);
// Update serverPosition and other variables
prevServerPosition = serverPosition;
prevServerTime = serverTime;
serverPosition = new Vector3(botPosData.x, botPosData.y, botPosData.z);
serverTime = Time.time;
currentLerpTime = 0f;
}
}
}
[System.Serializable]
private class BaseMessage
{
public string type;
}
[System.Serializable]
private class MovementData
{
public string type;
public string action;
public bool jump;
public bool sprint;
}
[System.Serializable]
private class LookData
{
public string type;
public float x;
public float y;
public float z;
}
[System.Serializable]
private class PositionData
{
public string type;
public float x;
public float y;
public float z;
}
[System.Serializable]
private class BotPositionData
{
public string type;
public float x;
public float y;
public float z;
}
}
Explanation:
WebSocket Initialization: A WebSocket instance is created using the serverUrl. The event handlers OnOpen, OnError, OnClose, and OnMessage are set up to handle the respective WebSocket events.
Sending Data: Movement, look direction, and position data are sent to the server using the SendText method of the WebSocket. Data is serialized into JSON format before sending.
Receiving Data: Bot position data is received from the server and handled in the HandleServerMessage method. The bot's position is then smoothly interpolated in the Update method.
Data Classes: Serializable classes are defined for each type of data sent and received to facilitate easy serialization and deserialization using Unity's JsonUtility.
Node.js Server
Make sure to install the ws WebSocket library by running npm install ws.
javascript
Explanation:
WebSocket Server Initialization: After starting the Express server, a WebSocket server (wss) is created using the same server instance. This allows it to share the same port.
Handling Connections: When a new client connects, it's added to the clients array. Incoming messages are parsed and appropriate handlers are called based on the type field in the message.
Broadcasting Bot Position: The broadcastBotCoordinates function sends the bot's current position to all connected clients every 100 milliseconds.
Message Handling: The handleMovement and handleLook functions process movement and look commands received from the client.
Data Format: Messages are expected to be JSON strings with a type property indicating the message type (movement, look, coordinates, or botPosition).
Notes and Recommendations:
WebSocket URL: Ensure the serverUrl in the Unity script points to the WebSocket URL (e.g., ws://localhost:8000).
Cross-Origin Resource Sharing (CORS): If you plan to run the client and server on different domains or ports, you may need to handle CORS policies.
Error Handling: Additional error handling and reconnection logic can be added to make the connection more robust.
Testing: After updating the code, thoroughly test the application to ensure the movement and synchronization work smoothly.
By modifying the movement to use WebSockets, you achieve a more efficient and responsive communication channel between the client and server, which is especially beneficial for real-time applications like games.
Let me know if you have any questions or need further assistance!
Not yet included in a published release.
const mineflayer = require('mineflayer');
const express = require('express');
const Vec3 = require('vec3');
const WebSocket = require('ws');
const app = express();
const port = 8000;
// Bot configuration
const botConfig = {
host: 'localhost',
port: 25565,
username: 'ChunkScanner',
version: '1.18.2'
};
const transparentBlocks = new Set([
'air', 'water', 'lava', 'chain', 'grass_block', 'grass', 'tall_grass'
]);
const transparentBlockPattern = new RegExp(
'(glass|leaves|fence|door|trapdoor|bars|rod|lantern|vine|sapling|coral|kelp|' +
'bamboo|mushroom|rail|torch|sign|banner|button|pressure|carpet|ladder)'
);
const CHUNK_SIZE = 16;
const CHUNK_RANGE = { X: 3, Z: 3 };
const ENABLE_CULLING = true;
const NEIGHBOR_OFFSETS = [
new Vec3(1, 0, 0), new Vec3(-1, 0, 0),
new Vec3(0, 1, 0), new Vec3(0, -1, 0),
new Vec3(0, 0, 1), new Vec3(0, 0, -1)
];
let bot;
let chunksLoaded = false;
let chunkCache = new Map();
let cachedBlockData = [];
app.use(express.json());
// Helper functions remain the same...
function isTransparentBlock(blockName) {
// ...
}
function isBlockExposed(bot, blockPos) {
// ...
}
function scanLoadedChunks(bot) {
// ...
}
function initializeBot() {
bot = mineflayer.createBot(botConfig);
bot.once('spawn', () => {
console.log('Bot spawned, waiting for chunks to load...');
});
bot.on('chunkColumnLoad', (point) => {
if (!chunksLoaded) {
chunksLoaded = true;
console.log('First chunk loaded at', point);
setTimeout(() => {
cachedBlockData = scanLoadedChunks(bot);
console.log(`Scanned ${cachedBlockData.length} blocks`);
chunkCache.clear();
}, 2000);
}
});
bot.on('error', console.error);
bot.on('kicked', console.log);
}
// HTTP endpoint for blocks remains the same
app.get('/blocks', (req, res) => {
res.json(cachedBlockData);
});
// Start the HTTP server
const server = app.listen(port, () => {
console.log(`Server listening on port ${port}`);
initializeBot();
});
// Initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });
// Store connected clients
let clients = [];
// WebSocket connection handling
wss.on('connection', (ws) => {
console.log('Client connected via WebSocket');
// Add the new client
clients.push(ws);
// Receive messages from clients
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
if (data.type === 'movement') {
handleMovement(data);
} else if (data.type === 'look') {
handleLook(data);
} else if (data.type === 'coordinates') {
// Handle coordinates received from client if needed
}
} catch (err) {
console.error('Error handling message:', err);
}
});
// Remove the client when it disconnects
ws.on('close', () => {
console.log('Client disconnected');
clients = clients.filter((client) => client !== ws);
});
});
// Broadcast bot's position to all connected clients
function broadcastBotCoordinates() {
if (bot && bot.entity) {
const position = bot.entity.position;
const posData = {
type: 'botPosition',
x: position.x,
y: position.y,
z: position.z
};
const message = JSON.stringify(posData);
clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
}
// Send position updates every 100 ms
setInterval(broadcastBotCoordinates, 100);
// Handle movement commands from the client
function handleMovement(data) {
const { action, jump = false, sprint = false } = data;
if (bot) {
try {
bot.clearControlStates();
switch (action) {
case 'forward':
bot.setControlState('forward', true);
break;
case 'backward':
bot.setControlState('back', true);
break;
case 'left':
bot.setControlState('left', true);
break;
case 'right':
bot.setControlState('right', true);
break;
case 'jump':
bot.setControlState('jump', true);
break;
case 'stop':
bot.clearControlStates();
break;
default:
console.log('Invalid action:', action);
break;
}
if (jump && action !== 'jump') {
bot.setControlState('jump', true);
}
if (sprint) {
bot.setControlState('sprint', true);
}
} catch (err) {
console.error('Movement handling error:', err);
}
}
}
// Handle look commands from the client
function handleLook(data) {
const { x, y, z } = data;
if (bot) {
try {
const targetPosition = new Vec3(x, y, z);
bot.lookAt(targetPosition, true);
} catch (err) {
console.error('Look handling error:', err);
}
}
}