我试图重复绘制在屏幕对角线的线。我在p5.js中是个新手,我不太确定如何正确构造随机函数调用,并在脚本内进行for循环以实现它。目前,它为startPt和endPt分配了随机的x和y,看起来好像是在循环并一遍又一遍地绘制同一条线。怎样才能使每个循环,带有新坐标的新行都绘制出来?
我还尝试将代码创建在start()循环内的startPt和endPt,但它会无限期地继续下去。
const margin = 50;
var loop_num = 100;
var startPt = {
x:0,
y:0,
domain:0,
}
var endPt = {
x:0,
y:0,
domain:0,
}
function setup() {
createCanvas (600, 400);
background (0);
create_startPt();
create_endPt();
// re-select endPt if it's not in diagonal domain of startPt
while (startPt.domain*endPt.domain != -2) {
endPt.x = random(0+margin, width-margin);
endPt.y = random(0+margin, height-margin);
endPt.domain = point_domain(endPt.x, endPt.y)
}
}
function draw() {
for (let i=0; i<=loop_num; i++) {
stroke (200);
line (startPt.x, startPt.y, endPt.x, endPt.y);
}
}
// check and assign domain number based on point location
function point_domain(x, y) {
if ((x>=0) && (x<width/2)) {
if ((y>=0) && (y<width/2)) {
return 1
}
else {return -1}
}
if ((x>=width/2) && (x<=width)) {
if ((y>=0) && (y<width/2)) {
return 2
}
else {return -2}
}
}
// create startPt
function create_startPt() {
startPt.x = random(0+margin, width-margin);
startPt.y = random(0+margin, height-margin);
// get domain tag of startPt
startPt.domain = point_domain(startPt.x, startPt.y)
}
// create endPt
function create_endPt() {
endPt.x = random(0+margin, width-margin);
endPt.y = random(0+margin, height-margin);
// get domain tag of startPt
endPt.domain = point_domain(endPt.x, endPt.y)
}
答案 0 :(得分:3)
您要在设置函数中调用create_endPt()
和create_startPt()
函数,因此不需要绘制函数,因为您不需要屏幕更新每一帧。
const margin = 50;
var loop_num = 100;
var startPt = {
x: 0,
y: 0,
domain: 0,
}
var endPt = {
x: 0,
y: 0,
domain: 0,
}
function setup() {
createCanvas(600, 400);
background(0);
for (let i = 0; i <= loop_num; i++) {
stroke(200);
create_startPt();
create_endPt();
line(startPt.x, startPt.y, endPt.x, endPt.y);
}
}
// check and assign domain number based on point location
function point_domain(x, y) {
if ((x >= 0) && (x < width / 2)) {
if ((y >= 0) && (y < width / 2)) {
return 1
} else {
return -1
}
}
if ((x >= width / 2) && (x <= width)) {
if ((y >= 0) && (y < width / 2)) {
return 2
} else {
return -2
}
}
}
// create startPt
function create_startPt() {
startPt.x = random(0 + margin, width - margin);
startPt.y = random(0 + margin, height - margin);
// get domain tag of startPt
startPt.domain = point_domain(startPt.x, startPt.y)
}
// create endPt
function create_endPt() {
endPt.x = random(0 + margin, width - margin);
endPt.y = random(0 + margin, height - margin);
// get domain tag of startPt
endPt.domain = point_domain(endPt.x, endPt.y)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js"></script>