我如何制作一款跟随游戏玩家的相机?我看的每个人的例子似乎都没有解释每件事情的作用和原因,所以我想问的是,如果有人可以让我作为一个快速的例子,并解释为什么每个部分都有任何原因。
答案 0 :(得分:1)
世界通常比窗口大,所以视图显示整个世界的特定区域。
/* vX, vY is position of viewport
vWidth, vHeight is size of viewport
In this case position of viewport is (0,0) and its size is 5x5 */
var vX = 0,
vY = 0,
vWidth = 5,
vHeight = 5;
/* color is used to draw a world map.
Map is a matrix which stores map information. Length of each row is width of
world map and number of rows is height of world map. Each value refer to color.*/
var color = ["#008000","#DAA520","#008080"];
var map = [[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,1,0,1,1,0],
[0,0,0,1,1,1,1,1,1,1],
[0,0,0,0,1,1,1,1,1,1],
[0,0,0,0,1,1,1,1,2,2],
[0,0,0,0,1,1,1,2,2,2],
[0,0,0,1,1,1,1,2,2,2],
[0,0,0,0,1,1,1,2,2,2],
[0,0,0,1,1,1,2,2,2,2]];
$(document).ready(function(){
/* get canvas element and get its context. Everything is drawn on context. */
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
/* canvas is a viewport. I'll set block size to 32x32px, so viewport size is
160x160px */
canvas.width = 160;
canvas.height = 160;
/* addEventlist */
document.addEventListener('keydown', function(e) {
switch (e.which) {
case 37:
if (vX > 0) vX--;
break;
case 38:
if (vY > 0) vY--;
break;
case 39:
if (vX< 10-vWidth) vX++;
break;
case 40:
if (vY< 10-vHeight) vY++;
break;
}
draw();
}, false);
draw();
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var x =0 ; x < vWidth;x++){
for(var y=0;y<vHeight;y++){
theX = x*32;
theY = y*32;
ctx.fillStyle=color[map[y+vY][x+vX]];
ctx.fillRect(theX,theY,32,32);
}
}
}
});