我正在练习代码的性质,它涉及到将现有程序转换为包含向量的程序。我所使用的原始代码是Walker对象的代码,该对象在“随机游走”过程中倾向于右转:
WalkerTendsToDownRight/Walker.pde
到目前为止,当我尝试运行代码时,Sketch选项卡就会打开,没有任何绘图。
该程序声明沃克对象的x和y组件,添加它们,呈现它们。然后是:
void step()
{
int rx = int(random(1));
int ry = int(random(1));
if (rx < 0.4)
{
x++;
} else
if (rx < 0.5)
{
x--;
}
else
if (ry < 0.9)
{
y++;
}
else
{
y--;
}
}
}
Walker w;
Walker location;
Walker velocity;
void setup()
{
size(200, 200);
background(255);
Walker w = new Walker(5, 5);
Walker location = new Walker(100, 100);
Walker velocity = new Walker(2.5, 3);
}
void draw()
{
location.add(velocity);
w.step();
w.render();
}发布于 2020-06-13 22:40:33
我想你是在用第一章“法典”的性质做这个练习
练习1.2 从介绍中选取一个walker示例,并将其转换为使用PVectors。
所以你想从WalkerTendsToDownRight实例开始,使用向量,对吗?保存步行器位置的x和y int字段可以替换为向量。我认为主要的草图代码可以保持不变。沃克代码可能如下所示:
class Walker {
PVector location;
Walker() {
location = new PVector(width / 2, height / 2);
}
void render() {
stroke(0);
strokeWeight(2);
point(location.x, location.y);
}
// Randomly move right (40% chance), left (10% chance),
// down (40% chance), or up (10% chance).
void step() {
float randomDirection = random(1);
if (randomDirection < 0.4) {
location.x++;
} else if (randomDirection < 0.5) {
location.x--;
} else if (randomDirection < 0.9) {
location.y++;
} else {
location.y--;
}
location.x = constrain(location.x, 0, width - 1);
location.y = constrain(location.y, 0, height - 1);
}
}在带向量实例的Walker on GitHub中,他们还使用了一个向量来存储步行者将要进行的移动。使用这种方法,step函数可能要短得多(同时保持对向右和/或向下移动的偏好):
void step() {
PVector move = new PVector(random(-1, 4), random(-1, 4));
location.add(move);
location.x = constrain(location.x, 0, width - 1);
location.y = constrain(location.y, 0, height - 1);
}如果您希望步行器继续执行小步骤,甚至可以向极限函数添加一个调用:
move.limit(1);https://stackoverflow.com/questions/62331822
复制相似问题