我希望粒子对象仅跟随运动中的mouseX和mouseY位置。我可以用mouseX和Y替换“原点”值吗?

  void run() {
    update();
    display();
  }

  // Method to update position
  void update() {
    velocity.add(acceleration);
    location.add(velocity);
    lifespan -= 2.0;
  }

    // Method to display
  void display() {
    stroke(0, lifespan);
    strokeWeight(2);
    fill(127, lifespan);
    ellipse(location.x, location.y, 12, 12);
  }

  // Is the particle still useful?
  boolean isDead() {
    if (lifespan < 0.0) {
      return true;
    } else {
      return false;
    }
  }
 }

最佳答案

看一下这个例子:

PVector pos;
PVector vel;
PVector acc;

void setup()
{
  size(400, 400);
  pos = new PVector(width / 2, height / 2);
  vel = new PVector(0, 0);
  acc = new PVector(0, 0);
}

void draw()
{
  background(255);
  followMouse();
  update();
  ellipse(pos.x, pos.y, 10, 10);
}

void followMouse()
{
  PVector mouse = new PVector(mouseX, mouseY);
  //calculating what acceleration would be needed to instantly reach the mouse
  acc = mouse.sub(pos);
  //reducing the acceleration to not reach the mouse instantly
  acc.mult(0.1);
}

void update()
{
  vel.add(acc);
  //dampening the velocity, so the ball gets slower when close to the mouse
  vel.mult(0.8);
  pos.add(vel);
}

07-24 20:03