xxxxxxxxxx
130
let tileAtlas;
let tileData;
let layers = [];
let tileW;
let tileH;
let atlasCols;
let atlasRows;
let worldCols;
let worldRows;
let worldW;
let worldH;
let canvasCols = 16;
let canvasW;
let canvasH;
let aspect = 16/9;
let M;
let collisionMap;
let cameraX = 0;
let cameraY = 0;
let cameraSpeed = 5;
function preload()
{
tileAtlas = loadImage("Assets/Images/GraceTiles.png");
tileData = loadJSON("Assets/Levels/ExampleLevel.json");
}
function setup()
{
tileW = tileData.tilewidth;
tileH = tileData.tileheight;
M = tileW;
atlasCols = tileAtlas.width / tileW;
atlasRows = tileAtlas.height / tileH;
worldCols = tileData.width;
worldRows = tileData.height;
worldW = worldCols * tileW;
worldH = worldRows * tileH;
canvasW = canvasCols * M;
canvasH = canvasW / aspect;
createCanvas(canvasW, canvasH);
AssembleWorld();
}
function draw()
{
background(0);
UpdateCamera();
push();
{
translate(-cameraX, -cameraY);
DrawWorld();
}
pop();
}
function UpdateCamera()
{
let minX = 0;
let minY = 0;
let maxX = worldW - canvasW;
let maxY = worldH - canvasH;
let dCamera = createVector();
if (keyIsDown(RIGHT_ARROW))
dCamera.x += 1;
if (keyIsDown(LEFT_ARROW))
dCamera.x -= 1;
if (keyIsDown(DOWN_ARROW))
dCamera.y += 1;
if (keyIsDown(UP_ARROW))
dCamera.y -= 1;
dCamera.normalize().mult(cameraSpeed);
cameraX = constrain(cameraX + dCamera.x, minX, maxX);
cameraY = constrain(cameraY + dCamera.y, minY, maxY);
}
function AssembleWorld()
{
for (const layerObject of tileData.layers)
{
let layer = createGraphics(worldW, worldH);
let indexArray = layerObject.data;
for (let i = 0; i < indexArray.length; ++i)
{
let index = indexArray[i];
let dx = (i % layerObject.width) * tileW;
let dy = int(i / layerObject.width) * tileH;
DrawTile(layer, index, dx, dy)
}
layers.push(layer);
}
}
function DrawTile(destImg, index, dx, dy)
{
--index;
let sx = (index % atlasCols) * tileW;
let sy = int(index / atlasCols) * tileH;
destImg.image(tileAtlas, dx, dy, tileW, tileH, sx, sy, tileW, tileH);
}
function DrawWorld()
{
for (const layer of layers)
DrawLayer(layer, 0, 0);
}
function DrawLayer(layer, x, y)
{
image(layer, x, y);
}