我是处理中的新编码员,请保持温柔。通常,我的代码会更长且更复杂,但是我为您准备了可以转换为我代码的简单代码。因此,代码为:
void setup()
{
size(1200, 800, P3D);
camZ = (height/2) / tan((PI*60.0)/360.0);
noStroke();
}
float camZ = 0;
void draw()
{
background(0);
camera(0, 0.0, camZ, //default camera position
0, 0, -500, //where it is looking to
0, 1, 0); //eye openness
rotateX(rotX + distY);
rotateY(rotY + distX);
scale(100);
drawHouse();
if(keyPressed)
{
if(key == 'w')
camZ -= 5;
else if(key == 's')
camZ += 5;
}
}
void drawHouse()
{
beginShape(QUADS);
fill(255,0,0);
//+Z face
vertex(-1, -1, 1); //upper left corner
vertex(1, -1, 1); //upper right corner
vertex(1, 1, 1); //bottom right corner
vertex(-1, 1, 1); //bottom left corner
fill(0,255,0);
//-Z face
vertex(-1, -1, -1); //upper left corner
vertex(1, -1, -1); //upper right corner
vertex(1, 1, -1); //bottom right corner
vertex(-1, 1, -1); //bottom left corner
fill(0,0,255);
//+X face
vertex(1, -1, 1); //upper left corner
vertex(1, -1, -1);
vertex(1, 1, -1);
vertex(1, 1, 1);
fill(255);
//-X face
vertex(-1, -1, 1); //upper left corner
vertex(-1, -1, -1);
vertex(-1, 1, -1);
vertex(-1, 1, 1);
fill(208,13,211);
//-Y face
vertex(-1, -1, 1);
vertex(1, -1, 1);
vertex(1, -1, -1);
vertex(-1, -1, -1);
fill(250,150,18);
//+Y face
vertex(-1, 1, 1);
vertex(1, 1, 1);
vertex(1, 1, -1);
vertex(-1, 1, -1);
endShape();
}
float rotX = 0, rotY = 0;
float lastX, lastY;
float distX, distY;
void mousePressed()
{
lastX = mouseX;
lastY = mouseY;
}
void mouseDragged()
{
distX = radians(mouseX - lastX);
distY = radians(lastY - mouseY);
}
void mouseReleased()
{
rotX += distY;
rotY += distX;
distX = distY = 0;
}
所以,我想在代码中给出的框内放一个灯。灯光应仅在盒子内部起作用。如何做到这一点?
很好的问题!这让我感到好奇,我不得不进行调查。恐怕这不在我的舒适范围内,但是我发现了一些可以帮助您的东西。
您的简化代码很棒,但是我进一步简化了代码,使事情变得更加明显。首先是代码,然后是一些解释:
float camZ = 0;
float rotX = 0, rotY = 0;
float lastX, lastY;
float distX, distY;
void setup()
{
size(1200, 800, P3D);
camZ = (height/2) / tan((PI*60.0)/360.0);
noStroke();
}
void draw()
{
background(0);
lights(); // We want to see what's outside the cube, too.
camera(0, 0.0, camZ, //default camera position
0, 0, -500, //where it is looking to
0, 1, 0); //eye openness
rotateX(rotX + distY);
rotateY(rotY + distX);
scale(100);
pointLight(255, 0, 0, 0, 0, 0); // this light is inside the cube. You cannot see it from outside (it's red, too)
box(2); //I made a white cube so the lightning will be more obvious
if (keyPressed)
{
if (key == 'w')
camZ -= 5;
else if (key == 's')
camZ += 5;
}
}
void mousePressed()
{
lastX = mouseX;
lastY = mouseY;
}
void mouseDragged()
{
distX = radians(mouseX - lastX);
distY = radians(lastY - mouseY);
}
void mouseReleased()
{
rotX += distY;
rotY += distX;
distX = distY = 0;
}
您是否尝试运行它?从外面看,盒子是灰白色的。但是,如果将相机移动到盒子中,则会看到墙壁有红色。这是正在发生的事情:
我用lights()照亮了草图。如果您想更改其值,它基本上是默认的ambientLight-对本演示而言,这无关紧要。如果注释该行,您会注意到在多维数据集之外看不到任何内容。
我在立方体中间添加了pointLight。一个点光源就像一个小灯泡:它是全向的。
我的点光源是红色的,因为它只会照亮红色的表面(在这种情况下,白色的墙壁看起来是红色的,因为白色在RGB中有红色的部分)。
我希望这可以帮助您正确地开始。祝你好运!