javascript 为什么在应该绘制的时候没有显示这些图块?

lf3rwulv  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(107)

我正在做一个游戏,我有基本的玩家移动和精灵动画,但是我想粘贴到背景上的草块似乎没有画出来。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// Variables
var tileSize = 32;
var tilex = Math.ceil(canvas.width / tileSize);
var tiley = Math.ceil(canvas.height / tileSize);
var tiles = [];
var player = [];
var playerState = 'idle';
var keyPresses = {};
var userSize = 128;

// Event Listeners
window.addEventListener('keydown', keyDownListener, false);
function keyDownListener(event) {
  keyPresses[event.key] = true;
};

window.addEventListener('keyup', keyUpListener, false);
function keyUpListener(event) {
  keyPresses[event.key] = false;
  playerState = 'idle';
};

//TileImages grass, stone, and structure
for (let i = 0; i < 156; i++) {
    tiles[i] = new Image();
    tiles[i].src = 'performanceTask Assets/tiles/tile' + i.toString() + '.png';
};

//Player Images idle and movement
for (let i = 0; i < 40; i++) {
    player[i] = new Image();
    player[i].src = 'performanceTask Assets/player/player' + i.toString() + '.png';
};

class Map {
    xTileLocation = 0;
    yTileLocation = 0;
    grassLand() {
        for (let i = 0; i < this.tiley; i++) {
            for (let j = 0; j< this.tilex; j++) {
                ctx.drawImage(this.tiles[0], this.xTileLocation, this.yTileLocation);
                this.xTileLocation += this.tileSize;
            };
            this.xTileLocation = 0;
            this.yTileLocation += this.tileSize;
        };
        this.xTileLocation = 0;
        this.yTileLocation = 0;
    };
};

class Player {
    x = canvas.width/2;
    y = canvas.height/2;

    tick = 0;
    playerImage = player;
    state = playerState;

    movementSpeed = 5;
    draw() {
        this.state = playerState

        // Movement
        if (keyPresses.w) {
            this.y -= this.movementSpeed;
            playerState = 'moving';
        }
        if (keyPresses.s) {
            this.y += this.movementSpeed;
            playerState = 'moving';
        }
        if (keyPresses.a) {
            this.x -= this.movementSpeed;
            playerState = 'moving';
        }
        if (keyPresses.d) {
            this.x += this.movementSpeed;
            playerState = 'moving';
        }



        // IDLE STATE
        if (this.state == 'idle') {
            if(this.tick==20 || this.tick > 20) {
                this.tick = 0;
            };
            ctx.drawImage(this.playerImage[this.tick], this.x - 64, this.y + 64, 128, 128);
        }
        else {
            if (this.state == 'moving') {
                if(this.tick < 21 || this.tick == 39) {
                    this.tick = 21;
                };
                ctx.drawImage(this.playerImage[this.tick], this.x -64, this.y + 64, 128, 128);
            }
        }
        this.tick = this.tick + 1;
    };
};

let user = new Player();
let map = new Map();
function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    map.grassLand();
    user.draw();
};
setInterval(gameLoop, 1000/24);

不工作的代码位于Map类中。
我试着通读了javascript文档,但没有发现任何东西。没有错误,似乎也没有什么工作。每个瓷砖是32px乘32px。

ljsrvy3e

ljsrvy3e1#

您决定使用Classes--这很好,但是要尝试将所有变量都保留在创建的对象中(如tileSize)。
grassLand方法中的逻辑有些不太合理,所以我重新制作了这部分。我希望你喜欢map和forEach函数,它们取代了for循环。
要注意的是,资产(如图像)需要加载之前,你可以把他们画在画布上。也许你应该有某种加载例程的所有资产之前,一切。

// SVG image for testing
var svgimg = "data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAgMTAiIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8ZGVmcz4KICAgIDxsaW5lYXJHcmFkaWVudCBpZD0iZzEiIGdyYWRpZW50VHJhbnNmb3JtPSJyb3RhdGUoMzIpIj4KICAgICAgPHN0b3Agb2Zmc2V0PSI1JSIgc3RvcC1jb2xvcj0iZ3JlZW4iIC8+CiAgICAgIDxzdG9wIG9mZnNldD0iOTUlIiBzdG9wLWNvbG9yPSJkYXJrZ3JlZW4iIC8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogIDwvZGVmcz4KPHJlY3Qgd2lkdGg9IjEwIiBoZWlnaHQ9IjEwIiBmaWxsPSJ1cmwoI2cxKSIgLz4KPC9zdmc+";
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

class Canvasmap {
  constructor(tileSize) {
    this.tileSize = tileSize;
    this.tilex = Math.ceil(canvas.width / tileSize);
    this.tiley = Math.ceil(canvas.height / tileSize);
    this.createTiles();
  }
  createTiles() {
    //TileImages grass, stone, and structure
    this.tiles = [...Array(this.tilex).keys()].map(x => {
      return [...Array(this.tiley).keys()].map(y => {
        let img = new Image();
        img.src = svgimg;
        /* if you need a numbered img src you can use
        the x and y variable src = `path/img${(x+1) * (y+1)}.png`
        or whatever fits*/
        return img;
      })
    });
  }

  grassLand() {
    this.tiles.forEach((arr, i) => {
      arr.forEach((img, j) => {
        let yTileLocation = this.tileSize * i;
        let xTileLocation = this.tileSize * j;
        ctx.drawImage(img, xTileLocation, yTileLocation, this.tileSize, this.tileSize);
      })
    });
  }
};

let map = new Canvasmap(32);

function gameLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  map.grassLand();
};

setInterval(gameLoop, 1000 / 24);
<canvas id="canvas" width="320" height="320"></canvas>

相关问题