To address the issues you've encountered—players not being visible to others, fullscreen game view, and adding gravity and jump mechanics—we need to make several modifications to both your client.js and server.js files. Below, I'll guide you through these changes step-by-step, including the necessary code adjustments.
1. Fixing Player Visibility to Others
Issue:
Players are not visible to others because the client maintains a separate localPlayer object, which isn't synchronized correctly with the server's players object. This causes discrepancies in player rendering across clients.
Solution:
- Assign a Unique ID to Each Client: Modify the server to send a unique identifier (
ownId) to each client upon connection.
- Synchronize Player Data: Remove the
localPlayer from the client and utilize the players object received from the server, which includes all players (including the local player).
Steps and Code Modifications:
Server-Side (server.js) Changes:
-
Send ownId to the Client:
After a client sends their name and the server registers them, send a message back containing their unique id. This allows the client to identify its own player within the players object.
// After adding the new player
players[ws.id] = {
id: ws.id,
name: playerName,
position: spawnPosition,
color: generateColor()
};
// Send initial data with ownId to the new client
ws.send(serialize({ ownId: ws.id, players, map_layout: currentMapLayout }));
// Broadcast to others about the new player
broadcast({ players, map_layout: currentMapLayout });
-
Ensure Broadcasting Includes All Players:
Ensure that every time a player's state changes, the server broadcasts the complete players object along with the map_layout.
(No additional changes needed beyond step 1, as the existing broadcast functionality already handles this.)
Client-Side (client.js) Changes:
-
Initialize clientId:
Introduce a clientId variable to store the unique identifier received from the server.
let clientId = null; // To store the client's unique ID
-
Remove localPlayer:
Since the server now manages player data, remove the separate localPlayer object.
// Remove the localPlayer object
// let localPlayer = {
// position: { x: 0, y: 0 },
// color: { r: 255, g: 255, b: 255 },
// name: "Player" + Math.floor(Math.random() * 1000) // Dynamic name
// };
-
Handle ownId in Server Messages:
Update the message handler to set the clientId when the server sends it.
socket.addEventListener("message", (event) => {
const data = deserialize(event.data);
if (!data) return;
if (data.ownId) {
clientId = data.ownId;
console.log(`Your client ID is ${clientId}`);
}
if (data.map_layout) {
mapLayout = data.map_layout;
drawMap();
}
if (data.players) {
players = data.players || players;
drawPlayers();
}
});
-
Update Player Movement to Use clientId:
Modify the movement controls to update the player's position within the players object and send updates to the server.
// Player movement
onKeyDown("left", () => {
if (clientId) {
players[clientId].position.x -= tileSize;
sendPlayerUpdate();
}
});
onKeyDown("right", () => {
if (clientId) {
players[clientId].position.x += tileSize;
sendPlayerUpdate();
}
});
onKeyDown("up", () => {
if (clientId) {
players[clientId].position.y -= tileSize;
sendPlayerUpdate();
}
});
onKeyDown("down", () => {
if (clientId) {
players[clientId].position.y += tileSize;
sendPlayerUpdate();
}
});
-
Update drawPlayers Function:
Ensure that all players, including the local player, are rendered correctly.
function drawPlayers() {
// Update existing player sprites or add new ones
Object.values(players).forEach(player => {
if (playerSprites[player.id]) {
// Update position and color
playerSprites[player.id].pos = vec2(player.position.x, player.position.y);
playerSprites[player.id].color = rgb(player.color.r, player.color.g, player.color.b);
} else {
// Add new player sprite
playerSprites[player.id] = add([
sprite("player"),
pos(player.position.x, player.position.y),
color(player.color.r, player.color.g, player.color.b),
scale(2), // Increased scale for larger player
area(),
layer("players"),
// Optional: Add a label for the player's name
text(player.name, { size: 8 }),
origin("center")
]);
}
});
// Remove sprites of disconnected players
for (let id in playerSprites) {
if (!players[id]) {
destroy(playerSprites[id]);
delete playerSprites[id];
}
}
}
2. Making the Game Fullscreen
Issue:
The game is currently set to a fixed size (800x600), which doesn't adapt to different screen sizes.
Solution:
Adjust the game dimensions to match the browser's viewport by using window.innerWidth and window.innerHeight. Additionally, handle window resize events to dynamically adjust the game's size.
Steps and Code Modifications:
-
Set Game Dimensions to Fullscreen:
const k = kaplay({
width: window.innerWidth,
height: window.innerHeight,
scale: 2,
});
-
Handle Window Resizing:
Ensure the game adjusts when the browser window is resized.
window.addEventListener('resize', () => {
// Adjust the game's canvas size
k.resize(window.innerWidth, window.innerHeight);
k.canvas.width = window.innerWidth;
k.canvas.height = window.innerHeight;
drawMap(); // Redraw the map to fit the new size
drawPlayers(); // Redraw players
});
-
Ensure Responsive Tile Placement:
Depending on the scaling, you might need to adjust tile sizes or positions to fit the new screen dimensions appropriately.
(Optional: Adjust tileSize based on scale or screen size if necessary.)
3. Adding Gravity and Jump Mechanics
Issue:
Players currently move instantly in response to key presses without any physical realism such as gravity or jumping.
Solution:
Implement basic physics for the local player, including gravity and the ability to jump. This involves managing velocity, applying gravity each frame, and updating the player's position accordingly. For simplicity, we'll handle physics on the client side for the local player, while other players' positions are updated based on server data.
Steps and Code Modifications:
-
Define Physics Constants and Variables:
const GRAVITY = 0.5;
const JUMP_FORCE = -10;
const MOVE_SPEED = 2;
let velocity = { x: 0, y: 0 };
let isOnGround = false;
-
Update Movement Controls for Physics:
Modify the movement controls to influence velocity instead of directly changing position.
// Player movement
onKeyDown("left", () => {
if (clientId) {
velocity.x = -MOVE_SPEED;
}
});
onKeyDown("right", () => {
if (clientId) {
velocity.x = MOVE_SPEED;
}
});
onKeyRelease("left", () => {
if (clientId && velocity.x < 0) {
velocity.x = 0;
}
});
onKeyRelease("right", () => {
if (clientId && velocity.x > 0) {
velocity.x = 0;
}
});
onKeyPress("space", () => {
if (clientId && isOnGround) {
velocity.y = JUMP_FORCE;
isOnGround = false;
sendPlayerUpdate();
}
});
-
Implement Physics in the Update Loop:
Apply gravity and update the player's position each frame. Also, detect ground collision to reset jump capability.
onUpdate(() => {
// Render all players
drawPlayers();
// Handle physics for the local player
if (clientId && players[clientId]) {
// Apply gravity
velocity.y += GRAVITY;
// Update position based on velocity
players[clientId].position.x += velocity.x;
players[clientId].position.y += velocity.y;
// Simple ground collision detection (assuming ground is at y = some value)
const groundLevel = 500; // Adjust based on your map
if (players[clientId].position.y >= groundLevel) {
players[clientId].position.y = groundLevel;
velocity.y = 0;
isOnGround = true;
} else {
isOnGround = false;
}
// Send updated position to the server
sendPlayerUpdate();
}
});
-
Enhance sendPlayerUpdate Function:
Optionally, you can send both position and velocity to the server for more accurate synchronization.
function sendPlayerUpdate() {
if (socket.readyState === WebSocket.OPEN && clientId) {
socket.send(JSON.stringify({
id: clientId, // Include player ID
position: players[clientId].position,
velocity: velocity
}));
}
}
-
Optionally, Handle Terrain and Collision with Tiles:
For more realistic physics, you'd want to handle collisions with the map tiles (e.g., platforms, walls). This requires more advanced collision detection and response, which depends on your game's specific mechanics and map design.
4. Complete Updated Code
Complete server.js:
const WebSocket = require('ws');
const { randomInt } = require('crypto'); // For generating random integers
const { promisify } = require('util');
const setTimeoutPromise = promisify(setTimeout);
const PORT = 25566;
const players = {};
const tileSize = 36; // Updated to match client
const mapLayouts = [
// Define map layouts here, example:
[
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
],
[
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
]
];
let currentMapLayout = mapLayouts[0];
const connections = [];
// Function to serialize data for sending to clients
function serialize(data) {
return JSON.stringify(data);
}
// Function to get a random spawn position
function getRandomSpawnPosition() {
const x = randomInt(0, currentMapLayout[0].length);
const y = randomInt(0, currentMapLayout.length);
return { x: x * tileSize, y: y * tileSize };
}
// Function to generate a random color
function generateColor() {
return {
r: randomInt(0, 256),
g: randomInt(0, 256),
b: randomInt(0, 256)
};
}
// Function to change map layout periodically
async function changeMapLayoutPeriodically() {
let mapIndex = 1; // Start from the second map since currentMapLayout is mapLayouts[0]
while (true) {
await setTimeoutPromise(60000); // Change map layout every 60 seconds
currentMapLayout = mapLayouts[mapIndex];
mapIndex = (mapIndex + 1) % mapLayouts.length;
console.log("Map layout changed.");
// Send the new map layout to all connected clients
broadcast({ players, map_layout: currentMapLayout });
}
}
// Broadcast utility
function broadcast(data) {
const message = serialize(data);
connections.forEach(ws => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(message);
}
});
}
// Create WebSocket server
const wss = new WebSocket.Server({ port: PORT });
wss.on('connection', (ws) => {
console.log('Client connected');
connections.push(ws);
// Assign a unique ID to each WebSocket connection
ws.id = generateUniqueID();
// Handle incoming messages from this client
ws.on('message', (data) => {
try {
const message = JSON.parse(data);
if (message.name) {
// Initial connection message with player name
const playerName = message.name;
// Generate a unique spawn position
const spawnPosition = getRandomSpawnPosition();
// Initialize new player with a unique color and position
players[ws.id] = { // Use the unique identifier as key
id: ws.id,
name: playerName,
position: spawnPosition,
color: generateColor()
};
// Send initial data with ownId to the new client
ws.send(serialize({ ownId: ws.id, players, map_layout: currentMapLayout }));
// Broadcast to others about the new player
broadcast({ players, map_layout: currentMapLayout });
} else if (message.position) {
// Position update message
if (players[ws.id]) {
players[ws.id].position = message.position;
// Broadcast updated positions to all clients
broadcast({ players, map_layout: currentMapLayout });
}
}
} catch (e) {
console.error(`Error processing data: ${e.message}`);
}
});
ws.on('close', () => {
console.log('Client disconnected');
// Remove player from players object
if (players[ws.id]) {
delete players[ws.id];
}
connections.splice(connections.indexOf(ws), 1);
// Inform remaining clients about the disconnected player
broadcast({ players });
});
});
// Function to generate a unique ID (simple incrementing counter or UUID)
let currentID = 1;
function generateUniqueID() {
return currentID++;
}
// Start server and change map layout periodically
console.log(`WebSocket server running on ws://localhost:${PORT}`);
changeMapLayoutPeriodically();
Complete client.js:
import kaplay from "kaplay";
import "kaplay/global";
const k = kaplay({
width: window.innerWidth, // Set to window's width
height: window.innerHeight, // Set to window's height
scale: 2,
});
const tileSize = 36; // Increased tile size for larger map
const serverHost = 'localhost';
const serverPort = 25566;
let mapLayout = [];
let players = {};
let clientId = null; // To store the client's unique ID
let socket;
let tileSprites = [];
let playerSprites = {};
// Physics variables for the local player
const GRAVITY = 0.5;
const JUMP_FORCE = -10;
const MOVE_SPEED = 2;
let velocity = { x: 0, y: 0 };
let isOnGround = false;
// Utility to deserialize data from server
function deserialize(data) {
try {
return JSON.parse(data);
} catch (error) {
console.error("Deserialization error:", error);
return null;
}
}
// Load sprites
loadSprite("tile", "/sprites/grass.png");
loadSprite("player", "/sprites/player.png");
// Handle window resize for fullscreen
window.addEventListener('resize', () => {
k.resize(window.innerWidth, window.innerHeight);
k.canvas.width = window.innerWidth;
k.canvas.height = window.innerHeight;
drawMap(); // Redraw the map to fit the new size
drawPlayers(); // Redraw players
});
scene("game", () => {
function drawMap() {
tileSprites.forEach(tile => tile.destroy()); // Clear previous tiles
tileSprites = []; // Reset tile sprites array
mapLayout.forEach((row, y) => {
row.forEach((tile, x) => {
if (tile === 1) {
const tileSprite = add([
sprite("tile"),
pos(x * tileSize, y * tileSize),
area(),
layer("tiles")
]);
tileSprites.push(tileSprite); // Store the tile sprite
}
});
});
}
function drawPlayers() {
// Update existing player sprites or add new ones
Object.values(players).forEach(player => {
if (playerSprites[player.id]) {
// Update position and color
playerSprites[player.id].pos = vec2(player.position.x, player.position.y);
playerSprites[player.id].color = rgb(player.color.r, player.color.g, player.color.b);
} else {
// Add new player sprite
playerSprites[player.id] = add([
sprite("player"),
pos(player.position.x, player.position.y),
color(player.color.r, player.color.g, player.color.b),
scale(2), // Increased scale for larger player
area(),
layer("players"),
// Optional: Add a label for the player's name
text(player.name, { size: 8 }),
origin("center")
]);
}
});
// Remove sprites of disconnected players
for (let id in playerSprites) {
if (!players[id]) {
destroy(playerSprites[id]);
delete playerSprites[id];
}
}
}
// Connect to the server
connectToServer();
// Player movement controls
onKeyDown("left", () => {
if (clientId) {
velocity.x = -MOVE_SPEED;
}
});
onKeyDown("right", () => {
if (clientId) {
velocity.x = MOVE_SPEED;
}
});
onKeyRelease("left", () => {
if (clientId && velocity.x < 0) {
velocity.x = 0;
}
});
onKeyRelease("right", () => {
if (clientId && velocity.x > 0) {
velocity.x = 0;
}
});
onKeyPress("space", () => {
if (clientId && isOnGround) {
velocity.y = JUMP_FORCE;
isOnGround = false;
sendPlayerUpdate();
}
});
// Send local player position to server
function sendPlayerUpdate() {
if (socket.readyState === WebSocket.OPEN && clientId) {
socket.send(JSON.stringify({
position: players[clientId].position,
velocity: velocity
}));
}
}
// Update loop
onUpdate(() => {
// Render all players
drawPlayers();
// Handle physics for the local player
if (clientId && players[clientId]) {
// Apply gravity
velocity.y += GRAVITY;
// Update position based on velocity
players[clientId].position.x += velocity.x;
players[clientId].position.y += velocity.y;
// Simple ground collision detection (assuming ground is at y = some value)
const groundLevel = 500; // Adjust based on your map
if (players[clientId].position.y >= groundLevel) {
players[clientId].position.y = groundLevel;
velocity.y = 0;
isOnGround = true;
} else {
isOnGround = false;
}
// Send updated position to the server
sendPlayerUpdate();
}
});
// Connect to the server function
function connectToServer() {
socket = new WebSocket(`ws://${serverHost}:${serverPort}`);
socket.addEventListener("open", () => {
console.log("Connected to server");
// Send player name upon connection
socket.send(JSON.stringify({ name: "Player" + Math.floor(Math.random() * 1000) }));
});
socket.addEventListener("message", (event) => {
const data = deserialize(event.data);
if (!data) return;
if (data.ownId) {
clientId = data.ownId;
console.log(`Your client ID is ${clientId}`);
}
if (data.map_layout) {
mapLayout = data.map_layout;
drawMap(); // Call drawMap() after updating the map layout
}
if (data.players) {
players = data.players || players;
drawPlayers(); // Call drawPlayers() after updating player data
}
});
socket.addEventListener("close", () => {
console.log("Disconnected from server");
});
}
});
// Start the game
go("game");
5. Additional Recommendations
-
Advanced Physics and Collision Detection:
- For more realistic movement, consider integrating a physics engine or implementing more sophisticated collision detection with the map tiles.
- Handle horizontal and vertical collisions separately to prevent players from passing through walls or floors.
-
Optimizing Network Traffic:
- Instead of sending position updates every frame, consider throttling updates (e.g., 20 times per second) to reduce bandwidth usage.
- Implement client-side prediction and server reconciliation for smoother movement, especially in cases of latency.
-
Security Considerations:
- Validate and sanitize all incoming data on the server to prevent malicious activities.
- Implement authentication if necessary, especially for larger or public servers.
-
Enhancements to Player Rendering:
- Differentiate the local player from others visually (e.g., outline, different color) for better user experience.
- Display player names above their sprites for easier identification.
-
Handling Multiple Map Layouts:
- Ensure that the map layout changes do not interfere with active gameplay. Consider pausing the game or synchronizing the map change across all clients seamlessly.
By implementing the above modifications, you should resolve the issues of player visibility, achieve a fullscreen game view, and introduce basic gravity and jump mechanics. This foundation can be further expanded with more advanced features and optimizations as needed.