首页 > 解决方案 > 如何以非常小的加速度和速度为运动物体设置动画?

问题描述

我正在尝试使用 Jpanels 模拟 N-Body 问题。我的力向量的工作方式就像两个物体在它们靠近时以它们应有的方式相互作用。但是,当两个身体相距很远时,它们的力量很小。JPanel 只允许 x 和 y 位置的增量至少为 1,这意味着速度必须是某个自然数。这意味着加速度也必须是某个自然数。

这导致了两个非常糟糕的解决方案:

  1. 将加速度从 double 转换为 int。这导致当两个物体相距很远时加速度为 0。

  2. 根据相对 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);
    }

}


标签: javasimulationgravity

解决方案


推荐阅读