3
I’m trying to build a camera system for a game that I intend to do in pure javascript, but I can’t produce the effect correctly. If anyone can see and fix it or guide me to read some tutorial would appreciate it very much!
Images used:
grass
: (http://i42.tinypic.com/2ljm6w9.png)sand
: (http://www.tibiawiki.com.br/images/7/7a/Sand_Tile.gif)
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>
I’m sorry for the lack of organization with OO, I’m new in programming and I’m also trying to do something simple and functional.
Note: I did not do the proper treatment of the movement with the arrows.
Thank you Victor! But now I have another question, what would be the most efficient way to prevent the movement to exceed the grid of Tiles?
– Matheus Henrique
@Matheushenrique Reply edited. :)
– Victor Stafusa
I’m still stuck in the code trying to understand everything hehe. I don’t quite understand why you switched the "<" by "<=" inside the FOR.
– Matheus Henrique