【问题标题】:What is causing the Mover to fall off the screen?是什么导致 Mover 从屏幕上掉下来?
【发布时间】:2019-05-20 19:52:21
【问题描述】:

添加“重力”会导致物体最终消失

老实说,我找不到错误。

移动类

class Mover {
  PVector acc;
  PVector loc;
  PVector vel;

  Mover() {
    loc = new PVector(width/2, height/2);
    vel = new PVector(0, 0);
    acc = new PVector(0, 0);
  }

  void update() {

    // Mouse
    //PVector mouse = new PVector(mouseX, mouseY);
    //mouse.sub(loc);
    //mouse.setMag(0.5);

    //F = M * A
    vel.add(acc);
    loc.add(vel);
    vel.limit(2);
  }

  void gravity() {
    PVector grav = new PVector(0, 9.8);

    acc.add(grav);
  }

  void wind(float wind_){
    PVector wind = new PVector(wind_,0);
    acc.add(wind);
  }
  void display() {
    stroke(0);
    fill(0, 255, 0);
    ellipse(loc.x, loc.y, 20, 20);
  }

  void bounce() {
    if ((loc.x > width) || (loc.x < 0)) {
      vel.x *= -1;
      acc.x *= -1;
    }
    if ((loc.y > height) || (loc.y < 0)) {
      vel.y *= -1;
      acc.y *= -1;
    }
  }

  void edges() {
    if (loc.x > width) {
      loc.x = 0;
    } else if (loc.x < 0) {
      loc.x = width;
    }
    if (loc.y > height) {
      loc.y = 0;
    } else if (loc.y < 0) {
      loc.y = height;
    }
  }
}

主文件

Mover b;


void setup() {
  size(800, 600);
  b = new Mover();
}

void draw() {
  background(255);
  b.gravity();
  b.wind(0.5);
  b.update();
  b.bounce();
  //b.edges();

  b.display();
}

我希望球最终会停留在屏幕底部

我得到的是它最终会消失。

另外,使发帖更容易的新助手让我在这个问题上添加了更多内容,但我所说的实际上就是我要说的全部

【问题讨论】:

    标签: java processing


    【解决方案1】:

    当检测到与地面或天花板的碰撞时,您必须将球的位置限制在窗口的范围内:

    class Mover {
    
        // [...]
    
        void bounce() {
    
            // [...]
    
            if ((loc.y > height) || (loc.y < 0)) {
                vel.y *= -1;
                acc.y *= -1;
                loc.y = loc.y > height ? height : 0; // limit y in the range [0, height]
            }
        }
    }
    

    由于重力不断地添加到加速度矢量 (b.gravity();) 中,如果位置低于地面,小球将略微无处可去。注意,如果速度矢量 (vel) 太小,无法将球举离地面,则条件loc.y &gt; height 再次满足,加速度再次转向acc.y *= -1


    一种选择是修复方法边缘:

    class Mover {
    
        // [...]
    
        void edges() {
            if (loc.x > width) {
                loc.x = width;
            } else if (loc.x < 0) {
                loc.x = 0;
            }
            if (loc.y > height) {
                loc.y = height;
            } else if (loc.y < 0) {
                loc.y = 0;
            }
        }
    

    并通过在draw()中调用b.edges()来限制小球的位置:

    void draw() {
        background(255);
    
        b.wind(0.5);
        b.gravity();
        b.update();
        b.bounce();
        b.edges();
    
        b.display();
    }
    

    【讨论】:

    • 非常感谢
    • 如果我只是将边缘类添加到反弹类中会起作用吗?制作边界类?
    • @CameronCampos 您必须修复方法edges。请参阅我现在添加的答案的第二部分。
    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2015-02-04
    相关资源
    最近更新 更多