处理:为什么此Walker对象未绘制?

问题描述 投票:0回答:1

我正在完成《代码本质》中的一项练习,其中涉及将现有程序转换为包含向量。我正在使用的原始代码是Walker对象的代码,该对象在“随机游走”期间趋于右侧:

https://github.com/nature-of-code/noc-examples-processing/blob/master/introduction/Exercise_I_1_WalkerTendsToDownRight/Walker.pde

到目前为止,我尝试运行代码时,Sketch选项卡打开,没有任何内容。

程序为Walker对象声明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();   

  }
java processing
1个回答
0
投票

我假设您正在Chapter 1 of the Nature of Code book中进行此练习:

练习1.2

从介绍中获得一个沃克示例,并将其转换为使用PVectors。

所以您想以WalkerTendsToDownRight example开头并使用向量,对吗?可以将保存步行者位置的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);
  }
}

[在GitHub的Walker with vector example中,他们还使用了一个向量来存储步行者将要进行的移动。使用这种方法,步进功能可能会短很多(同时保持向右和/或向下移动的偏好):

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);
© www.soinside.com 2019 - 2024. All rights reserved.