首页 > 解决方案 > 如何更改 p5.js 中 2d 对象的 z 坐标?(和其他东西)

问题描述

我正在尝试制作具有类似 3D 分层的 2D 游戏(例如不要一起挨饿)链接:https ://editor.p5js.org/TheDiamondfinderYT/full/pBfQMdgSd

但这就是我得到的(走到“树”)。两个问题迫在眉睫:

  1. 复制
  2. 边框叠加
  3. 树永远不会在方形帮助后面。

标签: javascriptp5.js

解决方案


对于初学者,您在绘制正方形之后绘制树,因此树将始终位于顶部。您需要一个条件来更改绘制对象的顺序。

为了解决您的“重复”问题,您不会在每次绘制时清除画布,因此您需要使用background(0);(或您想要的任何颜色)

要解决您的“边框叠加”问题,您需要使用noStroke()关闭笔触。

这是完整更新的代码:https ://editor.p5js.org/Samathingamajig/sketches/b5NcCuioK

// There's more stuff up here, setting up variables and such

function draw() {
  background(0); //  <===
  camera.lookAt(0, 0, 30, 0, 0, playerX-Xdrag, playerY-Ydrag);
  rectMode(CENTER);
  
  if (playerY >= 110) { //  <=== here, you would need to make variables for the tree's location
    noStroke(); //  <===
    fill(255);
    image(tree, 30, 30, 100, 100);
    fill(100);
    rect(playerX, playerY, 30, 30, 1);
  } else { //  <===
    noStroke(); //  <===
    fill(100);
    rect(playerX, playerY, 30, 30, 1);
    fill(255);
    image(tree, 30, 30, 100, 100);
  }

  // More stuff down here too, but just some logic making the variables change
}

同样在那个链接中,我更改了一些东西(不是功能方面的),例如添加分号、;修复缩进以及更改variable = variable + 5为减法。variable += 5-=

除了将图像修改为没有边框之外,对树的边框没有任何(使用代码)可以做,因为它上面有大约 5 个像素的黑色边框。


推荐阅读