I'm trying to build a camera system for a game that I plan to do in pure javascript, but I can not produce the effect correctly. If anyone can see and fix it or guide me to read some tutorial I would appreciate it very much!
Images used:
Code:
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
var grass = new Image();
var sand = new Image();
grass.src = "http://i42.tinypic.com/2ljm6w9.png";
sand.src = "http://www.tibiawiki.com.br/images/7/7a/Sand_Tile.gif";
var tsize = 32; //tile size
var mapArray = [[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1,1,1,1,1,1]];
//Cam configs
var camX = 0;
var camY = 0;
var camWidth = 320;
var camHeight = 160;
//others
var offsetX = 0;
var offsetY = 0;
function draw() {
requestAnimationFrame(draw);
var startCol = Math.floor(camX / tsize);
var endCol = startCol + (camWidth / tsize);
var startRow = Math.floor(camY / tsize);
var endRow = startRow + (camHeight /tsize);
offsetX = -camX + startCol * tsize;
offsetY = -camY + startRow * tsize;
console.log(startCol + "," + endCol + "," + startRow + "," + endRow);
for(var r = startRow; r < endRow; r++){
for(var c = startCol; c < endCol; c++){
var x = (c - startCol) * tsize + offsetX;
var y = (r - startCol) * tsize + offsetY;
if(mapArray[r][c] == 0) {
ctx.drawImage(grass, x, y);
}
if(mapArray[r][c] == 1) {
ctx.drawImage(sand, x, y);
}
}
}
}
document.addEventListener("keydown", function(e){
if(e.keyCode == 39) {
camX += 1;
}
if(e.keyCode == 37) {
camX -= 1;
}
});
draw();
<html>
<head>
<title>Scrolling Tiled Map</title>
</head>
<body>
<canvas id="canvas1" width="320" height="160" style = "border: 1px solid black;"></canvas>
<script src="javascript.js"></script>
</body>
</html>
Sorry for the lack of organization with OO, I'm new to programming and I'm also trying to do something simple and functional.
Note: I did not do the proper movement treatment with the arrows.