为什么我的角色无法在HTML5画布中呈现

因此,我尝试通过减少所有对象的x属性来“移动” HTML 5画布中的相机,但是将字符保持在同一位置,直到到达特定点(第三背景宽度的一半)为止。 )。当到达它时,所有对象都会停止让角色在画布上移动。但是,当到达那个点时,我的角色不会渲染(我可以通过在realX(向此对象添加或减去玩家的X速度)和画布中心之间切换角色的X来达到此目的。在这两个属性之间切换时,一旦我的角色超过了该点(第三张背景图像的一半),它还设置了其他对象(两个框和背景图像)x尚未到达该点的属性。已设置。

物理和其他所有功能都能完美运行,唯一的问题是角色无法渲染 我也尝试过手动设置每个所需的变量,但仍然无法正常工作。

您可以在repl.it上找到代码,script.js是唯一的功能js文件,save.js只是我在发生严重错误时用来保存代码的文件。

这是有问题的部分:

if ((player.pos.realx < (background[1].length * 800 - 800 - (player.width / 2))) && (player.pos.realx > 0)) {
    console.log("inside");
    player.pos.x = (canvas.width / 2) - (player.width / 2);
    for (let i = 0; i < background[1].length; i++) {
      ctx.drawImage(background[1][i].img,background[1][i].x -= player.velocity.x,-100,800,600);
    }
    for (let i = 0; i < background[0].length; i++) {
      ctx.drawImage(background[0][i].img,background[0][i].x -= player.velocity.x,600);
    }
    for (let i = 0; i < objects.length; i++) {
      ctx.fillStyle = objects[i].color;
      ctx.fillRect(objects[i].x -= player.velocity.x,objects[i].y,objects[i].width,objects[i].height);
    }
  } else if ((player.pos.realx > (background[1].length * 800 - 800 - (player.width / 2)))) {
    console.log("outside");
    player.pos.x = player.pos.realx;
    for (let i = 0; i < background[1].length; i++) {
      ctx.drawImage(background[1][i].img,background[1][i].x,background[0][i].x,600);
    }
    for (let i = 0; i < objects.length; i++) {
      ctx.fillStyle = objects[i].color;
      ctx.fillRect(objects[i].x,objects[i].height);
    }
  }
  //not displaying... outside
  ctx.fillStyle = player.color;
  ctx.fillRect(player.pos.x,player.pos.y,player.width,player.height);

还有一些其他变量和对象:

let objects = [new Box(250,200,50,"blue"),new Box(750,"green")];

let background = [[],[]];
for (let i = 0; i < 3; i++) {
  background[1].push(new Background(i * 800,600));
  background[1][i].img.src = "./pixelTree.png";
}
for (let i = 0; i < 3; i++) {
  background[0].push(new Background(i * (-800),600));
  background[0][i].img.src = "./pixelTree.png";
}

let player = {
  width: 50,height: 100,color: "red",pos: {
    x: 0,y: 0,realx: 0,},dir: {
    right: false,left: false,up: false,velocity: {
    x: 0,}
player.pos.x = (canvas.width / 2) - (player.width / 2);

function Box(x,y,width,height,color) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
  this.color = color;
}
function Background(x,height) {
  this.img = new Image();
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

感谢您的时间。

fankaoquan 回答:为什么我的角色无法在HTML5画布中呈现

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3133175.html

大家都在问