0

how would I go about making a camera that follows a player in a game? Everyone example I look doesn't seem to explain what each thing does and why, so what I'm asking if possible is if someone could make me a quick example of one and explain why each part is there any why.

1 Answer 1

1

A world is usually bigger than the window, so a view shows specific area of the whole world.

jsfiddle

/* 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);
            }
        }
    }

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.