Я создаю многопользовательскую игру Pong, используя веб -токеты (Fastify + WebSocket API) для школьного проекта, но я сталкиваюсь с проблемой, когда весла задержка, в то время как мяч движется плавно. Вот моя настройка: < /p>
Описание задачи
Движение мяча гладко и синхронизируется между клиентами < /p>
Движение весла имеет заметную задержку /задержку < /p>
Особенно плохая для лопата локального игрока (должна быть Instant) < /p>
Современная реализация < /p> (Br /p> (Br /> < /p> < /p>
. WebSocket): < /p>
function gameLogic(gameState) {
if (gameState.keypressd[0] === "w" && gameState.playerId === 1)
gameState.paddleLeftY -= 8;
if (gameState.keypressd[0] === "s" && gameState.playerId === 1)
gameState.paddleLeftY += 8;
if (gameState.keypressd[0] === "w" && gameState.playerId === 2)
gameState.paddelRightY = Math.max(0, gameState.paddelRightY - 8);
if (gameState.keypressd[0] === "s" && gameState.playerId === 2)
gameState.paddelRightY = Math.min(450, gameState.paddelRightY + 8);
if (flagX || (gameState.ballX >= 890 && gameState.ballY >= gameState.paddelRightY && gameState.ballY (msg) => {
try {
const gameState = JSON.parse(msg);
gameState.playerId = playerId;
const updatedState = gameLogic(gameState);
player1.send(JSON.stringify(updatedState));
player2.send(JSON.stringify(updatedState));
} catch (error) {
console.error('Invalid JSON format', error);
}
};
player1.on('message', handleMessage(player1, 1));
player2.on('message', handleMessage(player2, 2));
}
});
});
< /code>
Клиентский код: < /p>
const socket = new WebSocket('ws://localhost:5000/remoteGame');
window.onload = () => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
socket.onopen = () => {
console.log('connected');
}
socket.onmessage = (event) => {
console.log('[client] Message from server:', event.data);
};
socket.onclose = () => {
console.log('[client] Disconnected from server');
};
socket.onerror = (err) => {
console.error('[client] WebSocket error:', err);
};
let keys = {};
window.addEventListener('keydown', (key) => {
keys[key.key] = true;
})
window.addEventListener('keyup', (key) => {
keys[key.key] = false;
})
socket.onmessage = (event) => {
flow.updateGameState(event.data);
};
const flow = new FlowField(ctx, keys);
flow.animate();
}
class FlowField {
#ctx;
#width;
#height;
#keys;
#paddleStat;
#canvasWidth;
#canvasHeight;
constructor(ctx, keys) {
this.#width = 10;
this.#height = 150;
this.#canvasWidth = 900;
this.#canvasHeight = 600;
this.#ctx = ctx;
this.#keys = keys;
this.#paddleStat = {playerId: 1, paddleLeftY: 0,paddelRightY: 0, ballX: 0, ballY: 300,gameStat: 1, keypressd: []};
}
updateGameState(data) {
this.#paddleStat = JSON.parse(data);
}
#draw()
{
this.#ctx.clearRect(0, 0, this.#canvasWidth, this.#canvasHeight);
console.log(this.#paddleStat.paddleLeftY, this.#paddleStat.paddelRightY);
// paddle left
this.#ctx.fillRect(0, this.#paddleStat.paddleLeftY, this.#width, this.#height);
this.#ctx.strokeRect(0, this.#paddleStat.paddleLeftY, this.#width, this.#height);
//paddle right
this.#ctx.fillRect(890, this.#paddleStat.paddelRightY, this.#width, this.#height);
this.#ctx.strokeRect(890, this.#paddleStat.paddelRightY, this.#width, this.#height);
//ball
this.#ctx.beginPath();
this.#ctx.arc(this.#paddleStat.ballX, this.#paddleStat.ballY, 13, 0, Math.PI * 2);
this.#ctx.fill();
this.#ctx.stroke();
}
keysFunction()
{
if (this.#keys["w"] === true && this.#paddleStat.paddleLeftY > 0)
{
this.#paddleStat.keypressd.push("w");
}
if (this.#keys["s"] === true && this.#paddleStat.paddleLeftY < this.#canvasHeight - this.#height)
{
this.#paddleStat.keypressd.push("s");
}
}
ballPositionUpdate()
{
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(this.#paddleStat));
}
}
animate()
{
this.#draw();
this.keysFunction();
this.ballPositionUpdate();
requestAnimationFrame(this.animate.bind(this))
}
}
< /code>
Что я попробовал
Basic Websocket Communication (текущая реализация) < /p>
Простой прогноз на стороне клиента (но не может заставить его работать правильно) < /p>
Подробнее здесь: https://stackoverflow.com/questions/796 ... ultiplayer
Pong Game - Плачки отстают, а мяч плавно движется в многопользовательской среде WebSocket ⇐ Javascript
Форум по Javascript
1746051466
Anonymous
Я создаю многопользовательскую игру Pong, используя веб -токеты (Fastify + WebSocket API) для школьного проекта, но я сталкиваюсь с проблемой, когда весла задержка, в то время как мяч движется плавно. Вот моя настройка: < /p>
Описание задачи
Движение мяча гладко и синхронизируется между клиентами < /p>
Движение весла имеет заметную задержку /задержку < /p>
Особенно плохая для лопата локального игрока (должна быть Instant) < /p>
Современная реализация < /p> (Br /p> (Br /> < /p> < /p>
. WebSocket): < /p>
function gameLogic(gameState) {
if (gameState.keypressd[0] === "w" && gameState.playerId === 1)
gameState.paddleLeftY -= 8;
if (gameState.keypressd[0] === "s" && gameState.playerId === 1)
gameState.paddleLeftY += 8;
if (gameState.keypressd[0] === "w" && gameState.playerId === 2)
gameState.paddelRightY = Math.max(0, gameState.paddelRightY - 8);
if (gameState.keypressd[0] === "s" && gameState.playerId === 2)
gameState.paddelRightY = Math.min(450, gameState.paddelRightY + 8);
if (flagX || (gameState.ballX >= 890 && gameState.ballY >= gameState.paddelRightY && gameState.ballY (msg) => {
try {
const gameState = JSON.parse(msg);
gameState.playerId = playerId;
const updatedState = gameLogic(gameState);
player1.send(JSON.stringify(updatedState));
player2.send(JSON.stringify(updatedState));
} catch (error) {
console.error('Invalid JSON format', error);
}
};
player1.on('message', handleMessage(player1, 1));
player2.on('message', handleMessage(player2, 2));
}
});
});
< /code>
Клиентский код: < /p>
const socket = new WebSocket('ws://localhost:5000/remoteGame');
window.onload = () => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
socket.onopen = () => {
console.log('connected');
}
socket.onmessage = (event) => {
console.log('[client] Message from server:', event.data);
};
socket.onclose = () => {
console.log('[client] Disconnected from server');
};
socket.onerror = (err) => {
console.error('[client] WebSocket error:', err);
};
let keys = {};
window.addEventListener('keydown', (key) => {
keys[key.key] = true;
})
window.addEventListener('keyup', (key) => {
keys[key.key] = false;
})
socket.onmessage = (event) => {
flow.updateGameState(event.data);
};
const flow = new FlowField(ctx, keys);
flow.animate();
}
class FlowField {
#ctx;
#width;
#height;
#keys;
#paddleStat;
#canvasWidth;
#canvasHeight;
constructor(ctx, keys) {
this.#width = 10;
this.#height = 150;
this.#canvasWidth = 900;
this.#canvasHeight = 600;
this.#ctx = ctx;
this.#keys = keys;
this.#paddleStat = {playerId: 1, paddleLeftY: 0,paddelRightY: 0, ballX: 0, ballY: 300,gameStat: 1, keypressd: []};
}
updateGameState(data) {
this.#paddleStat = JSON.parse(data);
}
#draw()
{
this.#ctx.clearRect(0, 0, this.#canvasWidth, this.#canvasHeight);
console.log(this.#paddleStat.paddleLeftY, this.#paddleStat.paddelRightY);
// paddle left
this.#ctx.fillRect(0, this.#paddleStat.paddleLeftY, this.#width, this.#height);
this.#ctx.strokeRect(0, this.#paddleStat.paddleLeftY, this.#width, this.#height);
//paddle right
this.#ctx.fillRect(890, this.#paddleStat.paddelRightY, this.#width, this.#height);
this.#ctx.strokeRect(890, this.#paddleStat.paddelRightY, this.#width, this.#height);
//ball
this.#ctx.beginPath();
this.#ctx.arc(this.#paddleStat.ballX, this.#paddleStat.ballY, 13, 0, Math.PI * 2);
this.#ctx.fill();
this.#ctx.stroke();
}
keysFunction()
{
if (this.#keys["w"] === true && this.#paddleStat.paddleLeftY > 0)
{
this.#paddleStat.keypressd.push("w");
}
if (this.#keys["s"] === true && this.#paddleStat.paddleLeftY < this.#canvasHeight - this.#height)
{
this.#paddleStat.keypressd.push("s");
}
}
ballPositionUpdate()
{
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(this.#paddleStat));
}
}
animate()
{
this.#draw();
this.keysFunction();
this.ballPositionUpdate();
requestAnimationFrame(this.animate.bind(this))
}
}
< /code>
Что я попробовал
Basic Websocket Communication (текущая реализация) < /p>
Простой прогноз на стороне клиента (но не может заставить его работать правильно) < /p>
Подробнее здесь: [url]https://stackoverflow.com/questions/79601167/pong-game-paddles-lagging-while-ball-moves-smoothly-in-websocket-multiplayer[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия