代码如下:
改变setup中polygon生成函数变成你想要的迷宫,话说可以用这玩意来击败海军大将黄猿么?
- void setup() {
- size(300, 300);
- background(55);
- stroke(255);
- strokeWeight(1);
-
- Polygon[] polygons = new Polygon[4];
- polygons[0] = new Polygon(new Point[] {
- new Point(50, 30),
- new Point(20, 120),
- new Point(30, 270),
- new Point(230, 280),
- new Point(280, 170),
- new Point(250, 20)
- });
- polygons[1] = new Polygon(new Point[] {
- new Point(70, 80),
- new Point(120, 75),
- new Point(140, 120),
- new Point(90, 160),
- new Point(50, 130)
- });
- polygons[2] = new Polygon(new Point[] {
- new Point(60, 210),
- new Point(120, 190),
- new Point(110, 240),
- new Point(80, 230),
- });
- polygons[3] = new Polygon(new Point[] {
- new Point(200, 160),
- new Point(230, 180),
- new Point(180, 200),
- });
- for (int i=0; i<polygons.length; i++) {
- polygons[i].display();
- }
-
- Point point = new Point(200, 100);
- Light light = new Light(point, PVector.random2D());
- strokeWeight(4);
- point(point.x, point.y);
- for (int j=0; j<10; j++) {
- for (int i=0; i<polygons.length; i++) {
- check(light, polygons[i]);
- }
- strokeWeight(2.0/(j+1));
- light.display();
- float x = light.p.x+light.v.x*light.t;
- float y = light.p.y+light.v.y*light.t;
- PVector v = PVector.sub(light.v, PVector.mult(light.ln, 2*PVector.dot(light.v, light.ln)));
- light = new Light(new Point(x, y), v);
- }
- }
-
- void check(Light light, Polygon polygon) {
- for (int i=0; i<polygon.lines.length; i++) {
- Line line = polygon.lines[i];
- PVector v = new PVector(line.p.x-light.p.x, line.p.y-light.p.y);
- float location = PVector.dot(v, line.n);
- float direction = PVector.dot(light.v, line.n);
- if (direction<0) {
- float t = location/direction;
- float u = -PVector.dot(v, light.n)/PVector.dot(line.v, light.n);
- if (location<=0 && t<light.t && u>=0 && u<=1) {
- light.t = t;
- light.ln = line.n;
- }
- }
- }
- }
-
- class Polygon {
- Line[] lines;
- Polygon(Point[] points) {
- lines = new Line[points.length];
- for (int i=1; i<lines.length; i++) {
- lines[i-1] = new Line(points[i-1].x, points[i-1].y, points[i].x, points[i].y);
- }
- lines[lines.length-1] = new Line(points[points.length-1].x, points[points.length-1].y, points[0].x, points[0].y);
- }
- void display() {
- for (int i=0; i<lines.length; i++) {
- lines[i].display();
- }
- }
- }
-
- class Light {
- float t=1000;
- Point p;
- PVector v, n, ln;
- Light(Point p, PVector v) {
- this.p = p;
- this.v = v;
- this.v.normalize();
- n = new PVector(v.y, -v.x);
- n.normalize();
- }
- void display() {
- line(p.x, p.y, p.x+v.x*t, p.y+v.y*t);
- }
- }
-
- class Line {
- Point p;
- PVector v, n;
- Line(float x0, float y0, float x1, float y1) {
- p = new Point(x0, y0);
- v = new PVector(x1-x0, y1-y0);
- n = new PVector(y1-y0, x0-x1);
- n.normalize();
- }
- void display() {
- line(p.x, p.y, p.x+v.x, p.y+v.y);
- }
- }
-
- class Point {
- float x, y;
- Point(float x, float y) {
- this.x = x;
- this.y = y;
- }
- }
复制代码
授权转载自 任远媒体实验室
|