Java运动2d

时间:2011-04-18 15:40:14

标签: java 2d

我之前使用过这样的东西在2d项目中运动,并且它总是有效。我正在使用它,它给了我一些输出的正确角度和错误的角度。我认为我的三角中只有一些错误,我错了。我已经检查了大约一百万次。 Prolly只是自动纠正我脑子里的错误。这是一些示例输出和恶意代码。

this(x,y): (500.0, 250.0)
dest(x,y): (400.0, 300.0)
DeltX: 100.0
DeltY: -50.0
Angle: 0.46364760900080615 //about 26.56°, should be 206.56° (26.56+pi) i think
XVELOC: 0.08944272
YVELOC: 0.04472136

public void Update(long deltaTime){
        if(this.destination == null){
            return;
        }

        this.x += this.x_velocity * deltaTime;
        this.y += this.y_velocity * deltaTime;

        if(Math.abs(this.x-destination.x) < 1 && Math.abs(this.y-destination.y) < 1){
            destination.arrive(this);
        }
    }

    public void setPath(){
        if(this.destination == null){
            return;
        } 

        double delta_x = (double) (this.x-this.destination.x);
        double delta_y = (double) (this.y-this.destination.y);
        int sign_x = (int)Math.signum(delta_x);
        int sign_y = (int)Math.signum(delta_y);
        double radian_angle = Math.atan((delta_x/delta_y));
        if(sign_x > 0 && sign_y > 0)
            radian_angle += Math.PI;
        else if(sign_x > 0 && sign_y < 0)
            radian_angle += Math.PI/2;
        else if(sign_x < 0 && sign_y > 0)
            radian_angle += 3*Math.PI/2;

        System.out.println("DeltX: "+delta_x);
        System.out.println("DeltY: "+delta_y);
        System.out.println("Angle: "+radian_angle);

        this.x_velocity = this.max_velocity*(float)Math.cos(radian_angle);
        this.y_velocity = this.max_velocity*(float)Math.sin(radian_angle);

        System.out.println("XVELOC: "+x_velocity);
        System.out.println("YVELOC: "+y_velocity);
    }

1 个答案:

答案 0 :(得分:1)

尝试使用atan2 - 这是为了处理这个问题

double delta_x = (double) (this.x-this.destination.x);
double delta_y = (double) (this.y-this.destination.y);
double radian_angle = Math.atan2(delta_y,delta_x); // arguements are y,x not x,y

http://download.oracle.com/javase/6/docs/api/java/lang/Math.html#atan2%28double,%20double%29