I'm developing a game using the html5 canvas, but I've never used it before and I'm having difficulty creating a camera. The intention is that it is the same as agar.io, where the player is centered in the middle of screen and only the surrounding field is moved, a 3000x3000 field and the player screen that is rendered is only 25x25. I saw several methods of doing this but I ended up getting very confused with so much information. I prefer the method using Canva's translate, but I'm still having trouble being able to make the render. I'll show you how the code is. It's going to be a multiplayer game.
The logic of the game:
"use strict"
function createGame() {
const state = {
players: {},
fruits: {},
screen: {
width: 25,
height: 25
}
}
function addPlayer({ playerId, playerX, playerY }) {
state.players[playerId] = {
x: playerX,
y: playerY
};
}
function removePlayer({ playerId }) {
delete state.players[playerId];
}
function addFruit({ fruitId, fruitX, fruitY }) {
state.fruits[fruitId] = {
x: fruitX,
y: fruitY
};
}
function removeFruit({ fruitId }) {
delete state.fruits[fruitId];
}
function checkFruitCollision(playerId) {
const player = state.players[playerId];
for (const fruitId in state.fruits) {
const fruit = state.fruits[fruitId];
if (player.x === fruit.x && player.y === fruit.y) {
removeFruit({ fruitId });
}
}
}
function movePlayer(command) {
const commandsAccepted = {
ArrowUp: function(player) {
if (player.y - 1 >= 0) {
player.y -= 1;
}
},
ArrowDown: function(player) {
if (player.y + 1 < state.screen.height) {
player.y += 1;
}
},
ArrowLeft: function(player) {
if (player.x - 1 >= 0) {
player.x -= 1;
}
},
ArrowRight: function(player) {
if (player.x + 1 < state.screen.width) {
player.x += 1
}
}
}
const keyPressed = command.key;
const playerId = command.playerId;
const player = state.players[playerId];
const movingPlayer = commandsAccepted[keyPressed]
if (player && movingPlayer) {
movingPlayer(player);
checkFruitCollision(playerId);
}
}
return {
state,
movePlayer,
addPlayer,
removePlayer,
addFruit,
removeFruit
}
}
export default createGame;
Render logic:
"use strict"
function renderScreen(screen, game, requestAnimationFrame) {
const ctx = screen.getContext("2d");
ctx.clearRect(0, 0, screen.width, screen.height);
for (const playerId in game.state.players) {
const player = game.state.players[playerId];
ctx.fillStyle = "#4c7370";
ctx.fillRect(player.x, player.y, 1, 1);
}
for (const fruitId in game.state.fruits) {
const fruit = game.state.fruits[fruitId];
ctx.fillStyle = "#90a32a";
ctx.fillRect(fruit.x, fruit.y, 1, 1);
}
requestAnimationFrame(() => renderScreen(screen, game, requestAnimationFrame));
}
export default renderScreen;
```