gpt4 book ai didi

java - 处理(Java可视化语言): edge checking function fails when used with an array of objects

转载 作者:行者123 更新时间:2023-11-30 04:01:56 25 4
gpt4 key购买 nike

我正在阅读丹尼尔·希夫曼 (Daniel Shiffman) 的优秀著作《代码的本质》(The Nature of Code),并已完成对物体之间引力和斥力的模拟。重力效果很好,但我的物体直接飞出了屏幕。我想将它们限制在 Canvas 上。我正在使用前一章中编写的边缘检查函数,但它无法将任何对象保留在 Canvas 上。
我很想知道为什么。
有问题的函数是 Mover 类中的最后一个代码块。

class Mover {

PVector location;
PVector velocity;
PVector acceleration;
float mass;

float G = 0.4; //universal gravitational constant

Mover(float m, float x, float y) {
location = new PVector(x,y);
velocity = new PVector(1,0);
acceleration = new PVector(0,0);
mass = m;
}

PVector attract(Mover m) {

PVector force = PVector.sub(location,m.location);
float distance = force.mag();
distance = constrain(distance,5,25);

force.normalize();
float strength = ((G * mass * m.mass) / (distance * distance)*-1);
force.mult(strength);
return force;
}

void applyForce(PVector force) {
PVector f = PVector.div(force,mass);
acceleration.add(f);
}

void update() {
velocity.add(acceleration);
location.add(velocity);
acceleration.mult(0);
}

void display() {
stroke(0);
strokeWeight(2);
fill(0,100);
ellipse(location.x,location.y, mass*25 , mass*25);
}

void checkEdges() { // why doesn't this work?

if (location.x > width) {
location.x = width;
velocity.x *= -1;
} else if (location.x < 0) {
velocity.x *= -1;
location.x = 0;
}

if (location.y > height) {
velocity.y *= -1;
location.y = height;
} else if (location.y < 0) {
velocity.y *= -1;
location.y = 0;
}

}

}

//////////////////////////////////////////////////////////////////////

Mover [] movers = new Mover [10];

void setup() {
size(1000,1000);

for (int i = 0; i < movers.length; i++) {
movers[i] = new Mover(random(0.1,2),random(width),random(height)); //mass, loc.x, loc.y //each mover initialized randomly
}

}

void draw() {
background(255);

for(int i = 0; i < movers.length; i++){
for(int j = 0; j < movers.length; j++){
if(i != j){
PVector force = movers[j].attract(movers[i]); //Calculate attraction force
movers[i].applyForce(force); //Apply attraction force
}
}
movers[i].update();
movers[i].display();
}
}

最佳答案

您不应该在 Update() 内调用 checkEdges() 吗?如果不是这样,那么在你的主代码之间怎么样

  movers[i].update();
movers[I].checkEdges(); // check after the update and before the display
movers[i].display();

关于java - 处理(Java可视化语言): edge checking function fails when used with an array of objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21766864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com