如果对象旋转,其他对象将消失!p5.js



我是p5.js的初学者。这是我迄今为止的代码:

function setup() {
createCanvas(600, 600);
}
function draw() {
background(50, 168, 82);
road();
sidepath();
truck();
house();
tree();
}
function road() {
fill(66, 62, 61);
noStroke();
rect(200, 0, 220, 600);
fill(197, 222, 202);
rect(300, 50, 40, 70);
rect(300, 200, 40, 70);
rect(300, 350, 40, 70);
rect(300, 500, 40, 70);
}
function sidepath() {
fill(67, 230, 80);
rect(0, 0, 220, 600);
rect(400, 0, 220, 600);
}
function house() {
fill(245, 225, 110);
rect(80, 50, 55, 55, 3);
triangle(80, 50, 45, 80, 80, 105);
fill(67, 230, 80);
rect(92, 60, 30, 30); 
fill(245, 225, 110);
translate(width/6, height/120);
rotate(PI/3.5);
rect(5, 45, 13, 64, 3);
translate(width/5, height/90);
rotate(PI/2.4);
rect(60, 63, 13, 64, 3);
}
function tree() {
fill(78, 150, 84);
triangle(70, 420, 30, 450, 70, 480);
triangle(100, 410, 50, 450, 100, 490);
triangle(130, 400, 75, 450, 130, 500);
rect(130, 430, 38, 30);
}

即使我放置了树,它也不会出现,因为我在房子中使用了旋转。如果对旋转零件进行注释,则会显示树。但是,我能同时得到它们吗?

rotate()translate()这样的运算定义一个新的变换矩阵,并将当前矩阵与新矩阵相乘
如果只想对1个对象应用旋转,则必须在指定旋转之前用push保存当前矩阵,并在驱动对象之后用pop恢复矩阵。

伪代码:

push()
roatate(...)
// [...] draw object (e.g. rect())
pop()

问题是您调用的函数(如rotate()translate()(没有push()pop()来存储数据。rotate()translate还旋转和平移树,因为这两个函数在调用后会影响所有内容。解决此问题的方法是使用push()pop(),我建议首先了解这些函数,因为它们非常有用。

function house() {
fill(245, 225, 110);
rect(80, 50, 55, 55, 3);
triangle(80, 50, 45, 80, 80, 105);
fill(67, 230, 80);
rect(92, 60, 30, 30); 
fill(245, 225, 110);
push();
translate(width/6, height/120);
rotate(PI/3.5);
rect(5, 45, 13, 64, 3);
translate(width/5, height/90);
rotate(PI/2.4);
rect(60, 63, 13, 64, 3);
pop();
}

我只是添加了一个push()和一个pop(),所以rotatetranslate只影响房子。我建议阅读本页和本页。他们应该总结push()pop()的作用。

如果你有任何问题,我很乐意澄清。

最新更新