简体   繁体   中英

How can i draw tiles on canvas using p5.js

I am trying to make an html5 game using p5.js and first thing I tried to implement is to draw a tilemap but my code does not work.

I used nested loop to draw the tiles but I need something faster, I found an other algorithm that uses one dimensional array to draw tiles I tried that algo but it does not work and I dont know why?

let tileset;
let map = [
    0, 0, 0,
    0, 0, 0,
    1, 1, 1
];

function preload() {
    tileset = loadImage("./tileset.png");
}

function setup() {
    createCanvas(500, 500);
}

function draw() {
    background(0);
    drawTiles(map, 3, 11);
}

function drawTiles(map, cols, tilesize) {
    for (let i = map.length - 1; i > -1; --i) {
        let value = map[i];
        // source x , y
        let sx = (value % cols) * tilesize;
        let sy = Math.floor(value / cols) * tilesize;
        // distenation x , y
        let dx = (i % cols) * tilesize;
        let dy = Math.floor(i / cols) * tilesize;
        // render image
        image(tileset, sx, sy, tilesize, tilesize, dx, dy, tilesize, tilesize);
    }
}

You've swapped source and destination. In image the first rectangular area (parameters 2 -5) define the destination in the window and the second rectangular area (parameters 6 - 9) define the source rectangle in image ( tileset ):

image(tileset, sx, sy, tilesize, tilesize, dx, dy, tilesize, tilesize);

image(tileset, dx, dy, tilesize, tilesize, sx, sy, tilesize, tilesize);

Since the destination grid an and the source tileset have a different number of columns, the function drawTiles , needs 2 columns parameters ( d_cols , c_cols ):

function draw() {
    background(0);
    drawTiles(map, 3, 2, 11);
}
function drawTiles(map, d_cols, s_cols, tilesize) {
    for (let i = map.length - 1; i > -1; --i) {
        let value = map[i];
        // source x , y
        let sx = (value % s_cols) * tilesize;
        let sy = Math.floor(value / s_cols) * tilesize;
        // distenation x , y
        let dx = (i % d_cols) * tilesize;
        let dy = Math.floor(i / d_cols) * tilesize;
        // render image
        image(tileset, dx, dy, tilesize, tilesize, sx, sy, tilesize, tilesize);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM