java - 如何以非常小的加速度和速度为运动物体设置动画?
问题描述
我正在尝试使用 Jpanels 模拟 N-Body 问题。我的力向量的工作方式就像两个物体在它们靠近时以它们应有的方式相互作用。但是,当两个身体相距很远时,它们的力量很小。JPanel 只允许 x 和 y 位置的增量至少为 1,这意味着速度必须是某个自然数。这意味着加速度也必须是某个自然数。
这导致了两个非常糟糕的解决方案:
将加速度从 double 转换为 int。这导致当两个物体相距很远时加速度为 0。
根据相对 x 和 y 位置的 Math.Ceil() 或 Math.Floor() 加速度。这意味着即使两个物体相距很远,加速度也始终至少为 -1 或 1。
两种解决方案都很糟糕。
public class Body {
int mass;
int x;
int y;
int velx = 0;
int vely = 0;
int accx = 0;
int accy = 0;
int WIDTH ;
int HEIGHT ;
boolean fixed;
final int GFIELD = 20;
Space world;
public Body(int x, int y, int mass,boolean fixed, Space world) {
this.x = x;
this.y = y;
this.WIDTH=mass;
this.HEIGHT=mass;
this.mass = mass;
this.fixed=fixed;
this.world = world;
}
public double distanceFrom(Body other) {
return (Math.sqrt(Math.pow(x-other.x, 2) +Math.pow(y-other.y, 2)));
}
public void update() {
accx = 0;
accy = 0;
if(!fixed){
for (int i = 0; i < world.bodies.size(); i++) {
if((world.bodies.get(i).x!=this.x)&&(world.bodies.get(i).y!=this.y)){
Body otherBody = world.bodies.get(i);
double GMm = (GFIELD * mass * otherBody.mass);
double force = GMm/Math.pow(this.distanceFrom(otherBody), 2);
double forcex = force * ((otherBody.x-this.x)/distanceFrom(otherBody));
double forcey = force * ((otherBody.y-this.y)/distanceFrom(otherBody));
//my ceil and floor method, it sucks
if(this.x<otherBody.x){
accx+=(int)Math.ceil(forcex/mass);
}else if(this.x>otherBody.x){
accx+=(int)Math.floor(forcex/mass);
}
if(this.y<otherBody.y){
accy+=(int)Math.ceil(forcey/mass);
}else if(this.x>otherBody.x){
accy+=(int)Math.floor(forcey/mass);
}
}
}
velx += accx;
vely += accy;
}
public void draw() {
world.g.drawOval(x, y, WIDTH, HEIGHT);
}
}
解决方案
推荐阅读
- c++ - 我可以按值重新排序地图中的元素吗?C++
- ruby-on-rails - 在 UI 模式下在 Github 操作中运行 Capybara 测试
- r - 将字符串作为文字传递以创建图形对象
- c# - ASP.NET Core MVC 修改实体导致 NullReferenceException
- android - 如何在android的edittext中使第一个字符为数字,第二个字符为字母?
- azure - kubernetes 500内部服务器故障排除
- mysql - 如何编写查询以在 MySQL 中为逗号分隔的字符串添加前缀?
- javascript - 如何等待 AJAX 成功处理程序完成执行?
- javascript - 如何在 node-fetch 中一次发送三个数据对象
- master-theorem - 大师方法:分而治之