你如何随机选择xhouse
how you random for xhouse
大家好希望你们一切都好
我有问题,我不知道如何使用随机,以便每次刷新页面时我创建的房子的 X 位置发生变化,使房子出现在不同的 X 中。
谢谢
这是我的代码;
var floorPos_y;
var xhouse;
var yhouse;
function setup() {
createCanvas(1000, 755);
floorPos_y = height * 3 / 4; //NB. we are now using a variable for the floor position
xhouse = 0;
yhouse = 0;
var xhouse = random(100, width);
}
function draw() {
background(100, 155, 255); //fill the sky blue
// House Code
//xhouse = 30;
yhouse = 366;
noStroke();
fill(255);
text("house", 100, height * 0.6);
fill(255, 0, 0);
rect(xhouse, yhouse, 180, 200);//main body of the house
fill(165, 42, 42);
triangle(xhouse, yhouse, xhouse + 90, yhouse - 116, xhouse + 180, yhouse);// tope of the house
fill(255, 255, 220);
rect(xhouse + 5, yhouse + 24, 55, 60);
rect(xhouse + 110, yhouse + 24, 55, 60);
fill(0, 0, 230);
rect(xhouse + 60, yhouse + 114, 50, 80);
fill(255, 255, 30);
ellipse(xhouse + 100, yhouse + 164, 13, 13);
}
function mousePressed() {
xposition = mouseX
yposition = mouseY
}
请尝试正确格式化您的代码。现在很难阅读。也请尝试调试您的代码:在您尝试在 draw()
函数中使用它之前,我先打印出 xhouse
的值:
console.log("xHouse: " + xhouse);
这会告诉你 xhouse
是未定义的,这是一个相当大的提示。
仔细查看您的 xhouse
变量,您可能会注意到您在草图顶部 声明 一个名为 xhouse
的变量:
var xhouse;
到目前为止一切顺利。然后在 setup()
函数中,您声明 另一个名为 xhouse
的 变量,并设置其值:
var xhouse = random(100,width);
但请注意,因为您使用的是 var
关键字,所以这会创建一个与草图顶部的变量 不同的 变量。草图顶部的变量仍然没有价值。也就是说,它的值为undefined
.
要解决您的问题,您需要声明 草图顶部的变量,然后初始化 中的变量setup()
函数。也就是说,去掉setup()
函数中的var
关键字:
xhouse = random(100,width);
如果您遇到其他问题,请尝试通过打印出您正在使用的变量的值来调试您的问题。祝你好运。
大家好希望你们一切都好
我有问题,我不知道如何使用随机,以便每次刷新页面时我创建的房子的 X 位置发生变化,使房子出现在不同的 X 中。
谢谢
这是我的代码;
var floorPos_y;
var xhouse;
var yhouse;
function setup() {
createCanvas(1000, 755);
floorPos_y = height * 3 / 4; //NB. we are now using a variable for the floor position
xhouse = 0;
yhouse = 0;
var xhouse = random(100, width);
}
function draw() {
background(100, 155, 255); //fill the sky blue
// House Code
//xhouse = 30;
yhouse = 366;
noStroke();
fill(255);
text("house", 100, height * 0.6);
fill(255, 0, 0);
rect(xhouse, yhouse, 180, 200);//main body of the house
fill(165, 42, 42);
triangle(xhouse, yhouse, xhouse + 90, yhouse - 116, xhouse + 180, yhouse);// tope of the house
fill(255, 255, 220);
rect(xhouse + 5, yhouse + 24, 55, 60);
rect(xhouse + 110, yhouse + 24, 55, 60);
fill(0, 0, 230);
rect(xhouse + 60, yhouse + 114, 50, 80);
fill(255, 255, 30);
ellipse(xhouse + 100, yhouse + 164, 13, 13);
}
function mousePressed() {
xposition = mouseX
yposition = mouseY
}
请尝试正确格式化您的代码。现在很难阅读。也请尝试调试您的代码:在您尝试在 draw()
函数中使用它之前,我先打印出 xhouse
的值:
console.log("xHouse: " + xhouse);
这会告诉你 xhouse
是未定义的,这是一个相当大的提示。
仔细查看您的 xhouse
变量,您可能会注意到您在草图顶部 声明 一个名为 xhouse
的变量:
var xhouse;
到目前为止一切顺利。然后在 setup()
函数中,您声明 另一个名为 xhouse
的 变量,并设置其值:
var xhouse = random(100,width);
但请注意,因为您使用的是 var
关键字,所以这会创建一个与草图顶部的变量 不同的 变量。草图顶部的变量仍然没有价值。也就是说,它的值为undefined
.
要解决您的问题,您需要声明 草图顶部的变量,然后初始化 中的变量setup()
函数。也就是说,去掉setup()
函数中的var
关键字:
xhouse = random(100,width);
如果您遇到其他问题,请尝试通过打印出您正在使用的变量的值来调试您的问题。祝你好运。